var _gMeerMeerDWService = "BL";
var _gSMExtension = "SME";
var _jsMeerMeerDebugFile = "C:\\\\meermeer_js_debug.txt";

//error codes for uploading to testing server
var IDS_FILE_IN_MULTIPLE_SITES = 7068;
var IDS_SITE_NOSITEFORFILE = 7179;
var _currentPreviewSession = null;
var _bMarkForGC = false;//mark for GC.
var _gbEscapeBackSlash = true //fix for single quote with double blackslash

//remote server peer class
var _dwRemoteServerPeer = null;
//local file peer class
var _dwLocalFilePeer = null;

//get the application locale...since CSXS Host Env has licensedLanguage locale which is different from appLanguage.
//(e.g. en_US or en_GB)
function getAppLanguage()
{
    var appLocaleRetVal =  '<object>';
    appLocaleRetVal += '<property id="appLocale"><string><![CDATA[' + dw.getAppLanguage() + ']]></string></property>';      
    appLocaleRetVal += '<property id="status"><' + true + '/></property>';
    appLocaleRetVal += '</object>';
    return appLocaleRetVal; 
}

function initializeScript()
{
    //hide & show the meermeer panel to register the document edit handler
    dw.flash.requestStateChange(_gMeerMeerDWService, "Hide");
    dw.flash.requestStateChange(_gMeerMeerDWService, "Show");
    //DWfile.write(_jsMeerMeerDebugFile, "Meer Meer JS Debug");
    
    //initialize our classes
    _dwRemoteServerPeer = new DWRemoteServerJSPeer();
    _dwLocalFilePeer = new DWLocalFileJSPeer(); 

    //check if preview is pending
	var bHasPendingRequest = false;
	
    var initialPreviewObject = MM._BrowserLab_Init_Preview_Object;
    if (initialPreviewObject != null)
	{
		bHasPendingRequest = true;
	}

	//form the return value , returning the pending request
    var retVal = '<object>';
    retVal += '<property id="status"><' + bHasPendingRequest + '/></property>';                  
    retVal += '</object>';  
    return retVal;  
}

function checkForPendingQueuedPreviewRequest()
{
    //see if there is pending request queued from initial launch of panel
	var bRetStatus = false;
    var initialPreviewObject = MM._BrowserLab_Init_Preview_Object;
	previewDocArgs =  '<object>';    
	if (initialPreviewObject != null)
    {
		//form the pending preview request
		previewDocArgs += '<property id="localFileURI"><string><![CDATA[' + initialPreviewObject.localFileURI + ']]></string></property>';        
		previewDocArgs += '<property id="previewURI"><string><![CDATA[' + initialPreviewObject.previewURI + ']]></string></property>';
		previewDocArgs += '<property id="isRemoteOnly"><string><![CDATA[' + initialPreviewObject.isRemoteOnly + ']]></string></property>';

		//if we have pending request queued
		bRetStatus = true; 
 
	    //clear the first request
        MM._BrowserLab_Init_Preview_Object = null;
    }
	previewDocArgs += '<property id="status"><' + bRetStatus + '/></property>';
	previewDocArgs += '</object>';  
	return previewDocArgs;
}


function documentEdited()
{    
    var currentDocument = dw.getDocumentDOM();
    if (currentDocument)
    {
        var curDocURI = currentDocument.URL;
        var relatedDoc = null;        
		//get the active related file
        var relatedFilePath = dw.getActiveRelatedFilePath();        
        if (relatedFilePath.length)
        {
            currentDocument = dw.getActiveWindow();
            curDocURI = currentDocument.URL;            
        }   
        //is previewing the same file in web service
        var isPreviewingFileString = '<invoke name="isPreviewingFile" returntype="xml"><arguments><string><![CDATA[' + curDocURI + ']]></string></arguments></invoke>';
        var isPreviewingFile = dw.flash.controlEvent(_gMeerMeerDWService, isPreviewingFileString);      
        var bIsPreviewing = (isPreviewingFile == "<true/>");        
        if (bIsPreviewing)
        {
            //is file already marked dirty //then skip checks.
            var isDirtyFileString = '<invoke name="isDirtyFile" returntype="xml"><arguments><string><![CDATA[' + curDocURI + ']]></string></arguments></invoke>';
            var isDirtyFile = dw.flash.controlEvent(_gMeerMeerDWService, isDirtyFileString);        
            var bIsFileAlreadyMarkedDirty = (isDirtyFile == "<true/>");                             
                                  
            if (!bIsFileAlreadyMarkedDirty)
            {
                //send the dirty notification - if source code differ
                var onDocEditedNotifyString = '<invoke name="onDocEdited" returntype="xml"><arguments><string><![CDATA[' + curDocURI + ']]></string></arguments></invoke>';
                dw.flash.controlEvent(_gMeerMeerDWService, onDocEditedNotifyString);
            }
        }
    }
}


//called from ActionScript class.
function publishDocTestingServer(paramArgsAsString)
{
    var paramArray = decodeParamString(paramArgsAsString);
    
    var localFileURI = "";
    var previewURI = "";
    
    clearGC(); //clear GC if needed.    
    
    if (paramArray && paramArray.length == 2)
    {
        localFileURI = paramArray[0];
        previewURI = paramArray[1];     
    }   
    if (localFileURI == "null") //for null string
    {
        //empty local file uri
        localFileURI = "";
    }
    
    var retObject = _dwRemoteServerPeer.publishDoc(localFileURI, previewURI);
    
    //form the return value
    var retVal = '<object>';
    retVal += '<property id="status"><' + retObject.bUploadStatus + '/></property>';                    
    retVal += '<property id="cancelled"><' + retObject.bCancelled + '/></property>';                    
    retVal += '</object>';  
    return retVal;  
}

//called from ActionScript class.
function completedPreview() {
    //at some point we can bring the app (browser client) into focus here
    //form the return value
    var bRet = true;
    var retVal = '<object>';
    retVal += '<property id="status"><' + bRet + '/></property>';                   
    retVal += '</object>';  
    return retVal;  
}

//called from ActionScript class.
function signInCSXS()
{
    var aServiceExtension = null;   
    var housingPlugIn = MM.CSXS.GetHousingPlugIn(); 
    var bSMECreated = dw.flash.controlExists(_gSMExtension);
    if (!bSMECreated)
    {
        //create/load the adobe meermeer swf/js
        aServiceExtension = housingPlugIn.findExtension(_gSMExtension);
        aServiceExtension.loadExtension();              
    }
    else
    {
        //show the extension
        aServiceExtension = housingPlugIn.findExtension(_gSMExtension);
        aServiceExtension.showExtension();          
    }   
}


function getPreviewDoc(previewMode)
{
    var bRetStatus = true; //default is true.
    var aDocURI = null;
    var aPreviewURI = null;
    
    clearGC(); //clear GC if needed.        
    
    //active document preview
    var currentDocument = _dwLocalFilePeer.getMainDoc();
    if (currentDocument)
    {
        bRetStatus = _dwLocalFilePeer.checkDocPreConditions(currentDocument, previewMode);  
        if (bRetStatus)
        {
            aDocURI = currentDocument.URL;                                          
            aPreviewURI = _dwLocalFilePeer.getPreviewURI(aDocURI);       
			aPreviewURI =  dw.doURLEncoding(aPreviewURI, "", true, true);
        }
    }
    
    //form the args XML format
    previewDocArgs =  '<object>';
    previewDocArgs += '<property id="localFileURI"><string><![CDATA[' + aDocURI + ']]></string></property>';        
    previewDocArgs += '<property id="previewURI"><string><![CDATA[' + aPreviewURI + ']]></string></property>';
    previewDocArgs += '<property id="status"><' + bRetStatus + '/></property>';
    previewDocArgs += '</object>';  
    return previewDocArgs;
}

//encode the tag markup characters
function minDWEntityEncode(origStr)
{
    var retStr = origStr; 
    retStr = retStr.replace( RegExp("<", "g"), "&dwlt;"); 
    retStr = retStr.replace( RegExp(">", "g"), "&dwgt;");   
    if (_gbEscapeBackSlash)
    {       
        //escape the back slash character.
        var aRegExp = /\\\\/ig;
        retStr = retStr.replace(aRegExp, "&dwbackslash;");      
    }
    return retStr;
}

function decodeParamString(paramArgsAsString)
{
	//fix any single quote encoding character	
	paramArgsAsString = paramArgsAsString.replace(RegExp("&apos;", "g"), "'");
    var paramArray = paramArgsAsString.split(",");
    return paramArray;
}


function getLocalFileContent(localFileURI)
{
    var bRetStatus = true;
    var siteRelativeURI = "";
    var siteRelativeDisplayURI = "";
    var docSource = "";
    var bIsPausedLiveCode = false;
    var docContentType = "";
    var docCharSet = "";
    
    if (localFileURI == "null") //for null string
    {
        //empty local file uri
        localFileURI = "";
    }
    else
    {
    	localFileURI = localFileURI.replace(RegExp("&apos;", "g"), "'");    	
    }
    var bIsFileURI = (localFileURI && localFileURI.length);     
    var retObject = _dwLocalFilePeer.getLocalDocSource(localFileURI);   
    bRetStatus = retObject.bRetStatus;  
    if (retObject.bRetStatus)
    {
        bIsPausedLiveCode = retObject.bIsPausedLiveCode;
        docSource = retObject.docSource;        
        docContentType = retObject.docContentType;
        docCharSet = retObject.docCharSet;
        if (bIsFileURI)
        {
            //do url encoding
            siteRelativeURI = _dwLocalFilePeer.toSiteRelativeURI(retObject.currentDocument, localFileURI);
            siteRelativeDisplayURI = siteRelativeURI; //without encoding for display purpose
            siteRelativeURI = dw.doURLEncoding(siteRelativeURI, "", true, true);                        
        }       
    }   
                
    //form the return value
    var retVal = '<object>';
    retVal += '<property id="status"><' + bRetStatus + '/></property>';
    retVal += '<property id="paused"><' + bIsPausedLiveCode + '/></property>';          
    retVal += '<property id="docCharSet"><string><![CDATA[' + docCharSet + ']]></string></property>';
    retVal += '<property id="docSource"><string><![CDATA[' + minDWEntityEncode(docSource) + ']]></string></property>';
    retVal += '<property id="docContentType"><string><![CDATA[' + docContentType + ']]></string></property>';
    retVal += '<property id="siteRelativeURI"><string><![CDATA[' + siteRelativeURI + ']]></string></property>';     
    retVal += '<property id="siteRelativeDisplayURI"><string><![CDATA[' + siteRelativeDisplayURI + ']]></string></property>';       
    retVal += '</object>';  
    
    return retVal;              
}


//convert from requested resource uri to local file uri to read file contents
function readDependentFile(paramArgsAsString)
{       
    var mainFileURI = "";
    var requestedResourceURI = "";
    var paramArray = decodeParamString(paramArgsAsString);
    if (paramArray && paramArray.length == 2)
    {
        requestedResourceURI = paramArray[0];
        mainFileURI =   paramArray[1];
    }   
    //DWfile.write(_jsMeerMeerDebugFile, requestedResourceURI, "append");   
    var retObject = _dwLocalFilePeer.readDependentFile(requestedResourceURI, mainFileURI);  
    var statusCode = retObject.statusCode;
    var dependentFileLocalURI = retObject.dependentFileLocalURI;
    var docSource = retObject.docSource;
    var docContentType = retObject.docContentType;

        
    //form the return value     
    var retVal = '<object>';
    retVal += '<property id="status"><string><![CDATA[' + statusCode + ']]></string></property>';       
    retVal += '<property id="dependentFileLocalURI"><string><![CDATA[' + dependentFileLocalURI + ']]></string></property>';     
    retVal += '<property id="dependentFileSource"><string><![CDATA[' + minDWEntityEncode(docSource) + ']]></string></property>';        
    retVal += '<property id="docContentType"><string><![CDATA[' + docContentType + ']]></string></property>';       
    retVal += '</object>';
    
    //DWfile.write(_jsMeerMeerDebugFile, retVal, "append");
    
    return retVal;              
}


//--------------------------------------------------------------------
//FUNCTION:
//checkPreConditions
//
//DESCRIPTION:
//Determines if pre conditions are met for testing server preview
//
//ARGUMENTS:
//bIsTestingServer 
//
//RETURNS:
//boolean, true if pre-conditions are met else display a Javascript alert and returns false
//--------------------------------------------------------------------
function checkPreConditions(paramArgsAsString)
{
    var bPreConditionsMet = false;
    
    var localDocURI = "";
    var previewURI = "";
    var isTestingServer = "";
    var isRemoteOnly = "";
    
    var paramArray = decodeParamString(paramArgsAsString);    
    if (paramArray && paramArray.length == 4)
    {
        localDocURI = paramArray[0];
        previewURI =   paramArray[1];
        isTestingServer = paramArray[2];        
        isRemoteOnly = paramArray[3];
    }   
    var bIsTestingServer = (isTestingServer == "true"); //preference (local/remote)
    var bIsRemoteFileOnly = (isRemoteOnly == "true"); //remote file (e.g. remote tree inside DW)
    
    if (bIsTestingServer)
    {   
        bPreConditionsMet = _dwRemoteServerPeer.checkPreConditions(previewURI, bIsRemoteFileOnly);
    }       
    else
    {
        //pre-conditions are met
        bPreConditionsMet = _dwLocalFilePeer.checkPreConditions(previewURI, bIsRemoteFileOnly); 
    }
            
    //form the return value
    var retVal = '<object>';
    retVal += '<property id="status"><' + bPreConditionsMet + '/></property>';                  
    retVal += '</object>';  
    return retVal;  
}



function clearGC() 
{
    if (_bMarkForGC)
    {
        //force a Garbage Collection
        dw.forceGarbageCollection();
        _bMarkForGC = false;
    }
}

function openLocURIinBrowser(serviceURI)
{
    serviceURI += "?language=" + dw.getAppLanguage() + "&state=use";
    //call the dw.browseDocument since it communicates over DDE (Dynamic Data Exchange) technique
    //to request focus to browser tab to come in front , it launches in the primary browser
    //specified inside DW tool.
    dw.browseDocument(serviceURI);
}

//--------------------------------------------------------------------
//CLASS:DWBasePeer
// base class which 
//--------------------------------------------------------------------
function DWBasePeer()
{   
}

DWBasePeer.prototype =
{
    checkSitePreConditions : function()
    {       
        var bPreConditionsMet = true;
        //we need a DW site to be defined   
        var nSites = site.getSites();
        var bActiveSite = false;
        if (nSites.length > 0)
        {
            var currSite = site.getCurrentSite();
            if (currSite && (currSite.length > 0))
            {
                bActiveSite = true;
            }       
        }       
        if (bActiveSite == false)
        {
            //we need a testing to be defined.
            var defineTestingServerMsg = dw.loadString("meermeerdw/panel/defineSite");
            //alert(defineTestingServerMsg);
            var bRetVal = confirm(defineTestingServerMsg);
            if (bRetVal)
            {
                //launch a new site dialog
                site.newSite();
            }
            //fail to meet pre-conditions
            bPreConditionsMet = false;
        }   
        return bPreConditionsMet;
    },
    checkFilePreConditions : function(previewDocURI)
    {
        var bPreConditionsMet = true;
        //check for doc uri , if it valid for preview       
        if (previewDocURI == "null") //for null string
        {
            //empty local file uri
            previewDocURI = "";
        }                   
        var fileExt = dwscripts.getFileExtension(previewDocURI);
        fileExt = fileExt.toLowerCase();
        if (fileExt.length == 0)
        {
            //get the extension if extension is missing , assume it to be folder (which is non browser able), hence disable the preview
            var noDocSpecifiedMsg = dw.loadString("meermeerdw/panel/noDocSpecified");
            alert(noDocSpecifiedMsg);
            bPreConditionsMet = false; 
        }
        else if ((fileExt == "css") || (fileExt == "js") || (fileExt == "txt"))
        {
            //disable it for .css, .js files.
            var inValidFileExtensionMsg = dw.loadString("meermeerdw/panel/inValidFileExtension");
            alert(inValidFileExtensionMsg);
            bPreConditionsMet = false; 
        }   
        return bPreConditionsMet;
    },
    checkDocPreConditions: function(aDocument, previewMode)
    {
        //these conditions are for doc - open inside DW.
        var bRetStatus = true;
        if (aDocument && aDocument.URL.length == 0) 
        {
          //ask the user to save the document
          var saveMessage = dw.loadString("meermeerdw/panel/saveFile");
          if (confirm(saveMessage)) 
          {
              if (dw.canSaveDocument(dw.getDocumentDOM())) 
              {
                  dw.saveDocument(dw.getDocumentDOM());
              }           
              //still empty
              if (aDocument.URL.length == 0)
              {
                  bRetStatus = false; //unable to save file.
              }           
          }
          else
          {
              bRetStatus = false; //unable to save file.
          }
        }               
        if (bRetStatus)
        {
            //check if file belongs to site.
            bRetStatus = this.fileBelongsToSite(aDocument);
        }
        return bRetStatus;
    },
    fileBelongsToSite : function (aDocument)
    {
        var bRetStatus = true;
        if (aDocument != null)
        {
            aDocURI = aDocument.URL;            
            var aSite = site.getSiteForURL(aDocURI);
            if (aSite.length == 0)
            {
                bRetStatus = false; //unable to find a site containing the file.
                var fileNotInSiteMsgA = dw.loadString("meermeerdw/panel/fileNotInSite_A");
                var fileNotInSiteMsgB = dw.loadString("meermeerdw/panel/fileNotInSite_B");
                var fileName = dwscripts.getSimpleFileName(aDocURI);
                var fileExt = dwscripts.getFileExtension(aDocURI);
                fileName = fileName + "." + fileExt;
                fileNotInSiteMsgA = dwscripts.sprintf(fileNotInSiteMsgA, fileName);
                alert(fileNotInSiteMsgA + "\\n\\n" + fileNotInSiteMsgB);                
            }
        }
        return bRetStatus;
    },      
    IsRelatedFileDoc : function (absoluteFilePath)
    {
        absoluteFilePath = dw.doURLEncoding(absoluteFilePath, "", true);    
        if (absoluteFilePath && absoluteFilePath.length)
        {
            var nRelatedFiles;
            var relatedFileList = dw.getRelatedFiles(true); 
            var relatedFileIsOpen = false;
            if (relatedFileList.length && relatedFileList.length > 0) 
            {
                nRelatedFiles = relatedFileList.length; 
                for (var i=0;i< nRelatedFiles; i++) 
                {
                    if (absoluteFilePath == relatedFileList[i]) 
                    {
                        relatedFileIsOpen = true;
                        break;
                    }
                }
            }
        }
        return relatedFileIsOpen;
    },
    getMainDoc:function()
    {   
        var mainDocument = null; 
        var relatedFilePath = dw.getActiveRelatedFilePath();
        if (relatedFilePath.length)
        {
            //change the current document to parent html container instead of related file document  
            mainDocument = dw.getActiveWindow(); 
        }
        else
        {
            mainDocument = dw.getDocumentDOM();
        }
        return mainDocument;
    },
    IsTextDoc:function (aDocURI)
    {
        var bIsTextDoc = false;
        var fileExt = dwscripts.getFileExtension(aDocURI);
        fileExt = fileExt.toLowerCase();    
        if ((fileExt == "js") || (fileExt == "txt"))
        {
            bIsTextDoc = true;
        }
        return bIsTextDoc;
    },  
    getPreviewURI:function(aDocURI)
    {
        var aPreviewURI = aDocURI;          
        //if site is defined and site app url prefix (testing server) is defined
        var aSite = site.getSiteForURL(aDocURI);            
        if (aSite.length)
        {
            var serverURLPrefix = this.getServerURLPrefix(aSite);
            if (serverURLPrefix && serverURLPrefix != "http://")
            {
                aPreviewURI = dwscripts.getSiteRelativePath(aPreviewURI);
                aPreviewURI = aPreviewURI.replace(/\\\\|:/g, "/");          
                //append to url prefix.
                if (serverURLPrefix[serverURLPrefix.length - 1] != '/')
                {
                    //add slash if missing.
                    if (aPreviewURI.indexOf("/") != 0)
                    {
                        aPreviewURI = "/" + aPreviewURI;
                    }
                }
                else
                {
                    if (aPreviewURI.indexOf("/") == 0)
                    {
                        aPreviewURI = aPreviewURI.substr(1);
                    }
                }           
                aPreviewURI = serverURLPrefix + aPreviewURI;            
            }   
        }
        return aPreviewURI;
    },
    fileIsCurrentlyOpenInsideDW : function (absoluteFilePath)
    {
        var openFilesArr = dw.getDocumentList(); 
        var fileIsOpen = false;
        var nOpenFiles;
        var i;
        // note: openFilesArr is an array of currently open document objects
        if (openFilesArr.length && openFilesArr.length > 0) 
        {
            nOpenFiles = openFilesArr.length; 
            for (i=0;i<nOpenFiles;i++) 
            {
                if (absoluteFilePath == openFilesArr[i].URL) 
                {
                    fileIsOpen = true;
                    break;
                }
            }
        }
        return fileIsOpen;      
    },
    toSiteRelativeURI : function(aDocument, localFileURI)
    {
        if (!aDocument && localFileURI.length)
        {
            //load the document - to resolve the site relative URL Prefix
            aDocument = dw.getDocumentDOM(localFileURI);
        }       
        if (aDocument)
        {
            siteRelativeURI = aDocument.localPathToSiteRelative(localFileURI);
            //use this function since it is more full proof
            //alert("siteRelativeURI::" + siteRelativeURI);
        }
        else
        {
            //fallback
            siteRelativeURI = dwscripts.getSiteRelativePath(localFileURI);
        }
        siteRelativeURI = siteRelativeURI.replace(/\\\\|:/g, "/");
        return siteRelativeURI;
    },
    convertFromSiteRelativeToLocalPath : function (requestedResourceURI, localFileURI)
    {
        //convert for site relative to local uri
        // - first try the current site
        // - then try other sites inside DW (since it could be sub-site)
        var dependentFileLocalURI = "";     

        //get the site for which main file belongs
        var aSite = site.getSiteForURL(localFileURI);   
            
        if (aSite.length)
        {
            //check the current site
            if (site.getAppURLPrefixForSite(aSite) != "http://")
            {
                dependentFileLocalURI = site.siteRelativeToLocalPath(requestedResourceURI,aSite);
                if (dependentFileLocalURI.length)
                {
                    dependentFileLocalURI = dwscripts.filePathToLocalURL(dependentFileLocalURI);
                }
            }
            var curSiteRootURL = null;
            if (dependentFileLocalURI.length == 0)
            {
                //get the current site local root url
                curSiteRootURL = site.getLocalRootURL(aSite);       
                var curSiteLength = curSiteRootURL.length;
                if (curSiteRootURL[curSiteLength - 1] == '/')
                {
                    curSiteRootURL = curSiteRootURL.substring(0,curSiteLength -1);
                }               
                //form a completed path
                var aDependentFileLocalURI = curSiteRootURL + requestedResourceURI;
                //confirm if the dependent file exist
                if (DWfile.exists(aDependentFileLocalURI))
                {
                    dependentFileLocalURI = aDependentFileLocalURI;
                }       
            }

            //if still does not exist , look in sibling folders
            if (dependentFileLocalURI.length == 0)
            {
                //move up a parent
                var lastSlashIndex = curSiteRootURL.lastIndexOf("/");
                var parentSiteRootURL = curSiteRootURL.substring(0, lastSlashIndex);
                
                //get the site name for this parent url if defined inside DW.
                var parentSiteName = site.getSiteForURL(parentSiteRootURL);
                if (parentSiteName.length)
                {
                    //check the current site
                    if (site.getAppURLPrefixForSite(parentSiteName) != "http://")
                    {
                        dependentFileLocalURI = site.siteRelativeToLocalPath(requestedResourceURI, parentSiteName);
                        if (dependentFileLocalURI.length)
                        {
                            dependentFileLocalURI = dwscripts.filePathToLocalURL(dependentFileLocalURI);
                        }               
                    }
                }
                
                if (dependentFileLocalURI.length == 0)
                {
                    //form a completed path
                    var aDependentFileLocalURI = parentSiteRootURL + requestedResourceURI;
                    //confirm if the dependent file exist at sibling levels of site root folder
                    if (DWfile.exists(aDependentFileLocalURI))
                    {
                        dependentFileLocalURI = aDependentFileLocalURI;
                    }
                }
            }   
        }
        return dependentFileLocalURI;
    },
    getContentTypeFromURI : function (aDocURI, isDependentFile)
    {
        var aContentType = "";
        var fileExt = dwscripts.getFileExtension(aDocURI);
        if (fileExt && fileExt.length)
        {
            fileExt = fileExt.toLowerCase();    
            if (fileExt && fileExt.length)
            {
                fileExt = fileExt.toLowerCase();    
                if (fileExt == "js")
                {
                    aContentType = "text/javascript"; 
                }
                else if (fileExt == "css")
                {
                    aContentType = "text/css";
                }
                else if (fileExt == "swf")
                {
                    aContentType = "application/swf";
                }
                else if (fileExt == "gif")
                {
                    aContentType = "image/gif";
                }
                else if (fileExt == "png")
                {
                    aContentType = "image/png";
                }
                else if (fileExt == "tiff")
                {
                    aContentType = "image/tiff";
                }
                else if ( (fileExt == "jpg") || (fileExt == "jpeg"))
                {
                    aContentType = "image/jpeg";
                }
                else
                {
                    if (!isDependentFile)
                    {
                        aContentType = "text/html";
                    }
                }
            }
        }
        return aContentType;
    },
    getCharSet : function (aDocument)
    {
        var aCharSet = null;
        if (aDocument)
        {
            aCharSet = aDocument.getCharSet();
            if (aCharSet && aCharSet.length)
            {
                //to be appended to content type
                aCharSet = "; charset=" + aCharSet;             
            }
        }
        return aCharSet;
    },
    getCharSetOnly : function (aDocument)
    {
        var aCharSet = null;
        if (aDocument)
        {
            aCharSet = aDocument.getCharSet();
        }
        return aCharSet;
    },  
    getSiteIndex : function (aSiteName)
    {
      var siteIndex = -1;
      var siteSummarySection = "Sites\\\\-Summary";
      var noOfSites = dw.getPreferenceInt(siteSummarySection, "Number of Sites", 0);
      for (var i=0; i < noOfSites; i++)
      {
         siteSection = "Sites\\\\-Site" + i;
         siteName = dw.getPreferenceString(siteSection, "Site Name");
         if(siteName == aSiteName)
         {
            siteIndex = i;
            break;
         }  
      }
      return siteIndex;     
    },  
    getServerURLPrefix: function (aSite)
    {
        var serverURLPrefix = site.getAppURLPrefixForSite(aSite);
        /*var siteIndex = this.getSiteIndex(aSite);
        if (siteIndex != -1)
        {
            var siteSection = "Sites\\\\-Site" + siteIndex;
            var isTestingServerSelected = site.isTestingServerSelected();
            if (!isTestingServerSelected)
            {
                serverURLPrefix = dw.getPreferenceString(siteSection, "Root URL");
            }
            else
            {
                serverURLPrefix = dw.getPreferenceString(siteSection, "URL Prefix");
            }
        }*/   
        return serverURLPrefix;     
    },
    IsValidFileURI: function (aURI)
    {
        var bIsValidFile = false;
        if (aURI && aURI.length)
        {
            if ((aURI.indexOf("=") != -1) ||
                (aURI.indexOf(";") != -1) ||
                (aURI.indexOf("+") != -1) ||
                (aURI.indexOf("|") != -1))  
            {
                bIsValidFile = false;
            }
            else
            {
                bIsValidFile = true;
            }
        }
        return bIsValidFile;
    },
    trimURLParams : function (aURI)
    {
        var retURI = aURI;
        //look for "?" for URL Parameter
        var qIndex = retURI.indexOf("?");
        if (qIndex != -1)
        {
            //eliminate URL params;
            retURI = retURI.substring(0, qIndex-1);
        }       
        return retURI;
    },
    isEnabledRelatedDoc : function()
    {
        var bEnabledRelatedDoc = true;
        var strEnableRelateDoc = dw.getPreferenceString("General Preferences", "Show Related Docs");
        strEnableRelateDoc = strEnableRelateDoc.toLowerCase();
        if (strEnableRelateDoc == "false")
        {
            bEnabledRelatedDoc = false;
        }
        return bEnabledRelatedDoc;
    }
};

//--------------------------------------------------------------------
//CLASS:DWLocalFileJSPeer
//peer js calls which handle uploads to Remote file/server
//--------------------------------------------------------------------
function DWLocalFileJSPeer()
{
    
}
DWLocalFileJSPeer.prototype = new DWBasePeer();

//list of dynamic feeds.
DWLocalFileJSPeer._dynamicFeedExts = new Array("cfm","cfml","cfc","asp","jsp","jst","aspx","ascx","asmx","php","php3","php4","php5");

DWLocalFileJSPeer.prototype.checkPreConditions = function(previewDocURI, bIsRemoteFileOnly)
{
    //checks if all pre-conditions are met for local file use case
    var bPreConditionsMet = false;			
    if (!bIsRemoteFileOnly)
    {
        bPreConditionsMet = this.checkSitePreConditions(); //check the site pre-conditions
        if (bPreConditionsMet)
        {
            bPreConditionsMet = this.checkFilePreConditions(previewDocURI); //check the file pre-conditions     
        }
		if (bPreConditionsMet)
		{			
			//get document.			
			var bIsDynamic = false;			
			var aDoc = this.getMainDoc();			
			if (aDoc)
			{
				var designViewMode =  aDoc.getDesignViewMode();
				if (designViewMode == "editable")
				{				
					//check if server side page, if so the user needs to be live view mode to use this feature with dynamic content.
					var fileExt = dwscripts.getFileExtension(previewDocURI);
					for (var i=0; i < DWLocalFileJSPeer._dynamicFeedExts.length; i++)
					{
						if (DWLocalFileJSPeer._dynamicFeedExts[i] == fileExt)
						{
							bIsDynamic = true;
							break;
						}
											
					}					
					//if it is dynamic page - warn the user - that dynamic page needs to be in live view.
					if (bIsDynamic)
					{
						var dynamicPageMsg = dw.loadString("meermeerdw/panel/dynamicPageMessage");
						alert(dynamicPageMsg);
						bPreConditionsMet = false; 									
					}
				}
			}			
		}
    }
    else
    {
        bPreConditionsMet = true; //since it remote file we can skip the above checks.
    }
    return bPreConditionsMet;
}

DWLocalFileJSPeer.prototype.getLocalDocSource = function(localFileURI)
{   
    var retObject = new Object();
    retObject.bRetStatus = true;
    retObject.bIsPausedLiveCode = false;
    retObject.docSource = "";
    retObject.docContentType = ""; //default to empty.
    retObject.docCharSet = ""; //default to empty -> which default to UTF-8 in AS
    
    var bIsFileURI = (localFileURI && localFileURI.length); 
    var currentDocument = null; 
    if (bIsFileURI)
    {
        //check if the document is open inside DW (as top level documents)
        if (this.fileIsCurrentlyOpenInsideDW(localFileURI))
        {
            currentDocument = dw.getDocumentDOM(localFileURI);
        }
    }
    else
    {
        //get the current document
        currentDocument = this.getMainDoc();
    }   
    
    if (currentDocument)
    {
        //get content type from DW doc.
        retObject.docContentType = this.getContentTypeFromURI(currentDocument.URL, false) + this.getCharSet(currentDocument);
        retObject.docCharSet = this.getCharSetOnly(currentDocument); 
        
        //get the source of the document loaded in memory
        if (currentDocument.getDesignViewMode() == "live")
        {
            //get source in live view
            retObject.docSource = currentDocument.browser.getSource();
            retObject.bIsPausedLiveCode = true;
        }
        else
        {
            //get source in edit view
            retObject.docSource =  currentDocument.source.getText();
        }       
    }
    else
    {
        //did not find open document
        //use the DWfile object to read the file contents
        if (bIsFileURI)
        {
            retObject.docSource = DWfile.read(localFileURI);
        }
        else
        {
            retObject.bRetStatus = false;
        }
    }   
    
    //set the current doc in ret Object
    retObject.currentDocument = currentDocument;
    
    return retObject;
}

DWLocalFileJSPeer.prototype.readDependentFile = function(requestedResourceURI, mainFileURI)
{   
    var retObject = new Object();   
    retObject.statusCode = "0";  //failure
    retObject.docSource = "";
    retObject.dependentFileLocalURI = "";
    retObject.docContentType = ""; //default to empty.          
    var dependentFileLocalURI = ""; 
    
    //do url decoding
    requestedResourceURI = dw.doURLDecoding(requestedResourceURI);
    //trim url parameters
    requestedResourceURI = this.trimURLParams(requestedResourceURI);    
    var bIsValidFileURI = this.IsValidFileURI(requestedResourceURI);    
    if (bIsValidFileURI)
    {
        if (requestedResourceURI.charAt(0) == '/') // site relative path
        {
            retObject.dependentFileLocalURI = this.convertFromSiteRelativeToLocalPath(requestedResourceURI, mainFileURI);       
            var fileExt = dwscripts.getFileExtension(retObject.dependentFileLocalURI);
            var bIsFile = (fileExt.length > 0); //eliminate folder.
            if (retObject.dependentFileLocalURI.length && bIsFile)
            {
                if (DWfile.exists(retObject.dependentFileLocalURI))
                {           
                    retObject.statusCode = "100"; //translated from site relative to local file uri, open inside flex code since it is not loaded/opened inside DW 
                    retObject.docContentType = this.getContentTypeFromURI(retObject.dependentFileLocalURI, true);
                }
                else
                {           
                    retObject.statusCode = "404"; //unable to locate dependent file
                }
            }
            else
            {
                retObject.statusCode = "404"; //unable to locate dependent file
            }
        }
        else
        {
            //all dependent file begin with "/"
            retObject.statusCode = "404"; //unable to locate dependent file     
        }
    }
    else
    {
        //not a valid file chars
        retObject.statusCode = "404"; //unable to locate dependent file     
    }
    
    //check if dependent file is open in DW Editor, get is *unsaved* content.
    if (retObject.statusCode != "404")
    {
        if (retObject.dependentFileLocalURI.length > 0)
        {                       
            if (this.IsRelatedFileDoc(retObject.dependentFileLocalURI) || this.fileIsCurrentlyOpenInsideDW(retObject.dependentFileLocalURI))
            {
                var bIsLiveMode = false;
                var bRelatedDocEnabled = this.isEnabledRelatedDoc();
                var mainDocument = dw.getDocumentDOM(mainFileURI);
                if (mainDocument.getDesignViewMode() == "live")
                {
                    bIsLiveMode = true;
                }               
                if ((!bIsLiveMode) || (bIsLiveMode && !bRelatedDocEnabled))
                {
                    //doc - is open inside DW.
                    //in live view when related doc is enabled (opening dependent file like css using getDocumentDOM takes the
                    //live view out of its frozen state due to reload.
                    var dependentFileDoc = dw.getDocumentDOM(retObject.dependentFileLocalURI);
                    if (dependentFileDoc)
                    {
                        retObject.docSource = dependentFileDoc.source.getText();
                        retObject.statusCode = "200"; //has doc contents which are more current than the one stored on user disk
                        retObject.docContentType = this.getContentTypeFromURI(retObject.dependentFileLocalURI, true);
                    }
                }
            }
        }
        else
        {
            //not found.
            retObject.statusCode = "404"; //unable to locate dependent file
        }
    }
    return retObject;
}



//--------------------------------------------------------------------
//CLASS:DWRemoteServerJSPeer
//peer js calls which handle uploads to Remote file/server
//--------------------------------------------------------------------
function DWRemoteServerJSPeer()
{   
}
DWRemoteServerJSPeer.prototype = new DWBasePeer();

DWRemoteServerJSPeer.prototype.checkPreConditions = function(previewDocURI, bIsRemoteFileOnly)
{
    //checks if all pre-conditions are met for remote server use case
    //if site is defined and site app url prefix (testing server) is defined
    var bPreConditionsMet = false;

    if (!bIsRemoteFileOnly) //already has a site.
    {
        bPreConditionsMet = this.checkSitePreConditions(); //check the site pre-conditions  
        if (bPreConditionsMet)
        {       
            if (site.getAppURLPrefixForSite() && site.getAppURLPrefixForSite() != "http://")
            {
                bPreConditionsMet = true; 
            }
            else
            {
                //we need a testing to be defined.
                var defineTestingServerMsg = dw.loadString("meermeerdw/panel/defineTestingServer");
                var bRetVal = confirm(defineTestingServerMsg);
                if (bRetVal)
                {
                    //launch a new site dialog
                    site.showTestingServerSettings();
                }               
                bPreConditionsMet = false; 
            }
        }
    }
    else
    {
        bPreConditionsMet = true; //since it remote file we can skip the above checks.
    }
    
    if (bPreConditionsMet)
    {
        bPreConditionsMet = this.checkFilePreConditions(previewDocURI); //check the file pre-conditions
    }
    
    if (bPreConditionsMet)
    {
        //get document.
        var aDoc = this.getMainDoc();       
		if (aDoc)
		{
			if (aDoc.getDesignViewMode() == "live")
			{
				//get the filename part of the main document.
				var aDocFileName = aDoc.URL;        
				var slashIndex = aDocFileName.lastIndexOf("/");
				if (slashIndex != -1)
				{
					aDocFileName = aDocFileName.substring(slashIndex+1);
				}
            
				//get the filename part of the preview document.
				var previewDocFileName = previewDocURI;
				slashIndex = previewDocFileName.lastIndexOf("/");
				if (slashIndex != -1)
				{
					previewDocFileName = previewDocFileName.substring(slashIndex+1);
				}

				//if they match.
				if (aDocFileName == previewDocFileName)
				{
					//warn the user - that live view only works for Local Preview.
					var liveViewMsg = dw.loadString("meermeerdw/panel/liveViewMessage");
					alert(liveViewMsg);
					bPreConditionsMet = false;              
				}
			}       
		}
    }
    
    
    return bPreConditionsMet;
}

DWRemoteServerJSPeer.prototype.isRemoteServerSetUp = function()
{
        var bTestingServerURIDefined = (site.getAppURLPrefixForSite() && site.getAppURLPrefixForSite() != "http://");
        return bTestingServerURIDefined
}

DWRemoteServerJSPeer.prototype.publishDoc = function (localFileURI, previewURI)
{
    var retObject = new Object();
    
    var bUploadStatus = false;
    var bCancelled = false;
    if (this.isRemoteServerSetUp())
    {
        if (localFileURI && localFileURI.length)
        {
            //upload the page via the site configuration to "User Test Server"                      
            var bUpdateCopyOnServer = true;
            var bShowUpdateCopyOnServerWarningDlg = dw.getPreferenceString("Site Preferences", "Update Copy On Application Server", -1);
            bShowUpdateCopyOnServerWarningDlg = bShowUpdateCopyOnServerWarningDlg.toUpperCase();
            if (bShowUpdateCopyOnServerWarningDlg != "FALSE")
            {
                //to launch the dialog again.
                var updateCopyOnServerMsg = dw.loadString("meermeerdw/panel/uploadCopyOnTestServer");
                bUpdateCopyOnServer = this.askUploadToTestingServerOK(updateCopyOnServerMsg, "Site Preferences", "Update Copy On Application Server", -1);          
            }           
            if (bUpdateCopyOnServer)
            {
                var uploadStatus = site.put(localFileURI);
                //DWfile.write(_jsMeerMeerDebugFile, "upload status::" + uploadStatus, "append");
                if ((uploadStatus < 0) || (uploadStatus == IDS_SITE_NOSITEFORFILE) || (uploadStatus == IDS_FILE_IN_MULTIPLE_SITES))
                {
                    bUploadStatus = false;
                    if (uploadStatus == -1)
                    {
                        bCancelled = true;
                    }
                }       
                else
                {
                    bUploadStatus = true;
                }
            }
            else
            {
                bUploadStatus = false; //since the preference is not set to update copy on test server, user did not proceed to upload.
                bCancelled = true;
            }
        }
        else
        {
            bUploadStatus = false; //if the local file uri is null
        }
    }
    
    //attach the return values
    retObject.bUploadStatus = bUploadStatus;
    retObject.bCancelled = bCancelled;
    
    return retObject;
}

//--------------------------------------------------------------------
//FUNCTION:
//uploadToTestingServer
//
//DESCRIPTION:
//This function displays an informational dialog, with the 
//"don't show me this again option".  If the user selects this
//option, then the given preference is set, and the dialog will
//not be displayed the next time this function is called.
//
//Example:
//  askOkCancel("message",
//  "Extensions\\Objects\\NewThing","SkipNewThingWarning");
//
//ARGUMENTS:
//message - string - the message to display.  Please note that
//  returns should be included in the message.  This dialog does
//  not automatically wrap.
//prefSection - string - the section where this preference should
//  be stored
//prefKey - string - the name of the key in which this preference
//  should be stored
//
//RETURNS:
//if the user turned off the dialog return false
//also return false if the user dismisses the dialog
//otherwise return true
//--------------------------------------------------------------------              
DWRemoteServerJSPeer.prototype.askUploadToTestingServerOK = function(message, prefSection, prefKey, dontShowAgain)
{
    if (message && prefSection && prefKey)
    {    
     // check if the registryKey is already set
     var retVal = false
     // if not set, display the alert
     if (dontShowAgain == -1)
     {
       var cmdName = 'ConfirmDS.htm';
       var cmdFile = dreamweaver.getConfigurationPath() + '/Commands/' + cmdName;
       var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
       if (cmdDOM)
       {
         var cmdWin = cmdDOM.parentWindow; 
         // Pass one arg for OK/Cancel, or extra args to define btns
        if (dwscripts.IS_WIN)
        {
            cmdWin.render(message, MM.BTN_Yes, MM.BTN_No);
        }
        else
        {
            cmdWin.render(message, MM.BTN_No, MM.BTN_Yes);
        }   
        dreamweaver.popupCommand(cmdName);
        retVal = (MMNotes.Confirm_RESULT == MM.BTN_Yes); // Reference to confirm global result.        
         // now set the registry key based on the result
         dontShowAgain = MMNotes.Confirm_DONOTSHOW;
         if (dontShowAgain) 
         {
           dw.setPreferenceString(prefSection, prefKey, !dontShowAgain);
         }
       }
     }
     else
     {
       retVal = false ;
     }
    }  
    return retVal;
}   


