/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2010 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.
**************************************************************************/

//---------------   GLOBAL VARIABLES   ---------------

var helpDoc = MM.HELP_cmdNativeAppFrameworkSetup; //help API

// hide for PGPath for CS5.5. we may resurrect it later, but for now it gets copied to a fixed location
var g_AllowCustomPhoneGapPath = false;

//--------------------------------------------------------------------
// FUNCTION:
//   isDOMRequired()
//
// DESCRIPTION:
//  DW API called to determine if this menu item is available in code view
//
// ARGUMENTS: 
//   Nothing.
//
// RETURNS:
//   false because this doesnt' require a dom and can work in code view
//--------------------------------------------------------------------
function isDOMRequired()
{ 
	return false;
}

//--------------------------------------------------------------------
// FUNCTION:
//   commandButtons()
//
// DESCRIPTION:
//  DW API called to get the command Buttons for the dialog
//
// ARGUMENTS: 
//   Nothing.
//
// RETURNS:
//   Array of Buttons.
//--------------------------------------------------------------------
function commandButtons()
{
   return new Array("PutButtonsOnBottom", "OkButton defaultButton", dw.loadString('Startup/MMinit/MM.BTN_Save'), "if (saveSettings()) window.close()",
                    "PutButtonOnLeft", dw.loadString('Startup/MMinit/MM.BTN_Help'), "displayHelp()",
                    "CancelButton", dw.loadString('Startup/MMinit/MM.BTN_Cancel'), "window.close()" );
}

//--------------------------------------------------------------------
// FUNCTION:
//   initializeUI()
//
// DESCRIPTION:
//  Called when the page loads, it set the initial values of the form
//	fields and hides the fields that are not supported
//
// ARGUMENTS: 
//   Nothing.
//
// RETURNS:
//   Nothing.
//--------------------------------------------------------------------
function initializeUI()
{    
	document.getElementById("pathToPhoneGap").value = NativeAppFramework.getGlobalPathToPhoneGap();
	document.getElementById("androidSDKPath").value = NativeAppFramework.getGlobalPathToAndroidSDK();
	document.getElementById("iOSSDKPath").value = NativeAppFramework.getGlobalPathToiOSSDK();

	//Hide the settings that aren't relevant
    if( g_AllowCustomPhoneGapPath )
	{
		document.getElementById("pgPathSettingsGroup").style.display = "";
		document.getElementById("sdkSectionBreak").style.display = "";
	}
    
	if( !dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_ANDROID) )
	{
		document.getElementById("androidSettingsGroup").style.display = "none";
		document.getElementById("androidInstallSDKGroup").style.display = "none";
	}
	
	if( !dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_IPHONE) &&
		!dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_IPAD))
	{
		document.getElementById("iOsSettingsGroup").style.display = "none";
		document.getElementById("iOSInstallSDKGroup").style.display = "none";
	}

	window.resizeToContents();
}


//--------------------------------------------------------------------
// FUNCTION:
//   saveSettings()
//
// DESCRIPTION:
//   validates the input then saves the global settings
//
// ARGUMENTS: 
//   Nothing.
//
// RETURNS:
//   Nothing.
//--------------------------------------------------------------------
function saveSettings()
{
	var pathToPhoneGap = document.getElementById("pathToPhoneGap").value;

	var androidSDKPath = document.getElementById("androidSDKPath").value;
	var iOSSDKPath = document.getElementById("iOSSDKPath").value;
	
	var supportsAndroid = dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_ANDROID);
	var supportsiOS = dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_IPHONE) || dw.nativeAppFramework.getDeviceIsSupported(NativeAppFramework.DEVICE_IPAD);
	
	//run the validations before we save
	if( g_AllowCustomPhoneGapPath && !validateFolderPath(pathToPhoneGap, dw.loadString('NAF/configureAppFrameworks/pathToPhoneGap/label') ) ) 
		return false;
	
	var androidSDKInstalled = false;
	var iOSSDKInstalled = false;
    var attemptedInstall = false;
	
	if( supportsAndroid )
	{
		//If we also support iOS then don't alert if the validation fails
		if( validateFolderPath(androidSDKPath, supportsiOS ? "" : dw.loadString('NAF/configureAppFrameworks/androidSDKPath/label') ) )
		{
			//Special vaildation for Adnroid since we can install the SDK for the user
			if( validateAndroidSDK(androidSDKPath) )
			{
				androidSDKInstalled = true;
			}
			else
			{
				if (1 == dwscripts.askYesNo(dw.loadString('NAF/configureAppFrameworks/installAndroidSDK/askYesNo'), MM.BTN_Yes))
                {
					installAndroidSDK();
                    attemptedInstall = true;
                }

				androidSDKPath = document.getElementById("androidSDKPath").value;
				
				if(validateAndroidSDK(androidSDKPath) )
					androidSDKInstalled = true;
			}
		}
		
		if( !androidSDKInstalled && !supportsiOS )
		{
			//If we don't support iOS, and we're not installed, then we need to bail here
			return false;
		}
	}
	
	if(supportsiOS )
	{
		//If we also support Android then don't alert if the validation fails
		if( validateFolderPath(iOSSDKPath, supportsAndroid ? "" : dw.loadString('NAF/configureAppFrameworks/iOsDevToolsPath/label') ) )
		{
			if( validateiOSDevTools( iOSSDKPath ) )
			{
				//the Dev tools are installed, verify the SDKs are as well
                // note: we are interested in the sdk list for THIS path. not necessarilly for the one currently registered.
                if( dw.nativeAppFramework.getiOSSDKList(NativeAppFramework.DEVICE_ANY, iOSSDKPath).length > 0 )
				{
					iOSSDKInstalled = true;
				}
				else
				{
					alert( dw.loadString( 'NAF/configureAppFrameworks/installiOsSDKOnly/alert' ) );
					if( !androidSDKInstalled )
						return false;
				}
			}
			else if( !supportsAndroid )
			{
				alert( dw.loadString('NAF/configureAppFrameworks/installiOsSDK/alert') );
				return false;
			}
		}
		
		if( !supportsAndroid )
		{
			return false;
		}
	}
	
	//If neither is installed, go back and try and give a good alert, then bail
	if( !androidSDKInstalled && !iOSSDKInstalled )
	{
		if( androidSDKPath != "" )
		{
			if( !validateFolderPath(androidSDKPath, dw.loadString('NAF/configureAppFrameworks/androidSDKPath/label') ) )
				return false;
		}
		else if( iOSSDKPath != "" )
		{
			if( !validateFolderPath(iOSSDKPath, dw.loadString('NAF/configureAppFrameworks/iOsDevToolsPath/label') ) )
				return false;
		}
		
		// only complain if we didn't try to install Android SDK. installAndroidSDK() throws up its own alerts which take precedence.
		if (!attemptedInstall)
            alert( dw.loadString('NAF/configureAppFrameworks/requireOneSDK/alert'));
		return false;
	}
	
	NativeAppFramework.setGlobalPathToPhoneGap(pathToPhoneGap);
    
    // We shouldn't allow the user to save a bogus path, but a blank path simply
    // means we don't care about that respective device type.
    if( androidSDKInstalled || androidSDKPath == "")
		NativeAppFramework.setGlobalPathToAndroidSDK(androidSDKPath);
	if( iOSSDKInstalled || iOSSDKPath == "")
		NativeAppFramework.setGlobalPathToiOSSDK(iOSSDKPath);

	dw.nativeAppFramework.initFramework(false);    // pass true to force installs or updates even if target(s) already exist.

	return true;
}

//--------------------------------------------------------------------
// FUNCTION:
//   validateAndroidSDK()
//
// DESCRIPTION:
//  Called to validate the Android SDK. We just do a simple test
//	to see if the "android" tool is installed and assume the rest is good
//
// ARGUMENTS: 
//   androidSDKPath - the path to check
//
// RETURNS:
//   true if it looks valid.
//--------------------------------------------------------------------
function validateAndroidSDK(androidSDKPath)
{
	var fileUri = new DWUri();
	if( androidSDKPath.toString().indexOf("file://") == 0 )
		fileUri = new DWUri(androidSDKPath);
	else
		fileUri.localPathToURI(androidSDKPath + "/");
        
    fileUri = addSeperatorAsNeeded(fileUri);
        
	fileUri.chDir("tools/");
	if(navigator.platform == "Win32") 
		fileUri.chDir("android.bat");
	else
		fileUri.chDir("android");
	
	return ( DWfile.exists(fileUri) );
}

//--------------------------------------------------------------------
// FUNCTION:
//   validateiOSDevTools()
//
// DESCRIPTION:
//  Called to validate the Apple Dev tools. Checks to see if xcodebuild is installed
//
// ARGUMENTS: 
//   iOSSDKPath - the path to check. Checks to see if the tool
//                we need is installed.
//   
//
// RETURNS:
//   true if it looks valid.
//--------------------------------------------------------------------
function validateiOSDevTools(iOSSDKPath)
{
	var fileUri = new DWUri();
	fileUri.localPathToURI(iOSSDKPath + "/");
	fileUri.chDir("usr/bin/xcodebuild");
	
	return ( DWfile.exists(fileUri) );
}


//--------------------------------------------------------------------
// FUNCTION:
//   installAndroidSDK()
//
// DESCRIPTION:
//  downloads the androind SDK and installs it
//
// ARGUMENTS: 
//   androidSDKPath - the path to the android SDK
//
// RETURNS:
//   true if it's valid.
//--------------------------------------------------------------------
function installAndroidSDK()
{
	//this is the fileDepth of hte android SDK. WE need this much more space to install it
	var androidSdkFileDepth = 90;
	if( !dw.isConnectedToInternet() )
	{
		alert( dw.loadString('NAF/configureAppFrameworks/installNeedsToBeOnline/alert') );
		return false;
	}
	
	var sdkPath = new DWUri();
	var deletedFolder = false;
	var sdkPathStr = document.getElementById("androidSDKPath").value;
	if( dwscripts.trim(sdkPathStr).length == 0 )
	{
		sdkPathStr = browseForFolder("androidSDKPath");
		//If the user hit cancel to the browse dialog, we'll get an empty string
		if( sdkPathStr == "" )
		  return;
		
		sdkPath = new DWUri( sdkPathStr );
	}
	else
	{
		sdkPath.localPathToURI(sdkPathStr + "/");
	}
	
	var localPath = (navigator.platform == "Win32")  ? sdkPath.toLocalPath() : sdkPath.toLocalPathUnix();
	if( !validateFolderPath( localPath,  dw.loadString('NAF/configureAppFrameworks/androidSDKPath/label'), androidSdkFileDepth ) )
		return false;

	if (DWfile.exists(sdkPath)) 
	{
		if (!dwscripts.isFolderWritable(sdkPath) && navigator.platform == "Win32") {// we have a read only directory need write access
		  alert(dw.loadString('NAF/configureAppFrameworks/requireWriteAccess/alert'));
		  return false;
		}
			
		//This is a little hackish, but we need the API to create the folder for us. Since it's
		//already empty, it's safe to delete it.
		if( DWfile.listFolder(sdkPath).length == 0 )
		{
			DWfile.remove(sdkPath);
			deletedFolder = true;
		}
		
		//If this isn't a completely empty then put the SDK in a sub-dir 
		if( DWfile.listFolder(sdkPath).length > 0 )
		{
			
			if( validateAndroidSDK( sdkPath ) )
			{
				//check and see if the user want to replace this
				if( 1 != dwscripts.askYesNo( dw.loadString('NAF/configureAppFrameworks/installAndroidSDKOverwrite/askYesNo'), MM.BTN_Yes) )
					return true;
			}
			else
			{
				//Add a new subdir for this SDK
				sdkPath.chDir("android-sdk/");
				var i = 1;
				while( i < 20 && DWfile.exists( sdkPath ) )
					sdkPath.chDir("android-sdk-" + i + "/");
				//on mac we expressly want the unix form of the local path
				document.getElementById("androidSDKPath").value = (navigator.platform == "Win32")  ? sdkPath.toLocalPath() : sdkPath.toLocalPathUnix();
			}
		}
	}
	
	localPath = (navigator.platform == "Win32")  ? sdkPath.toLocalPath() : sdkPath.toLocalPathUnix();
	
	// we cant run the android tools from a remote volume.
	if( dw.nativeAppFramework.pathIsOnServerVolume(localPath) )
	{
		alert( dw.loadString('NAF/configureAppFrameworks/pleaseSelectSDKOnLocalVolume/alert') );
		return false;
	}

	var installResult = dw.nativeAppFramework.installAndroidSDK(localPath, g_androidSDKSourceURL, g_androidMaxSDKVersion, true);
	
	// if the user cancels, forget we were here
	if (installResult == NativeAppFramework.RESULT_CANCEL)
	{
		// if we deleted an existing (empty) folder, restore it.
		if( deletedFolder )
			DWfile.createFolder(sdkPath);
		// restore the original value of the path field
		document.getElementById("androidSDKPath").value = NativeAppFramework.getGlobalPathToAndroidSDK();
		return false;
	}
	else if (installResult == NativeAppFramework.RESULT_FAIL)
	{
		if( deletedFolder )
			DWfile.createFolder(sdkPath);
		alert( dw.loadString('NAF/configureAppFrameworks/installAndroidSDKFailed/alert') );
		return false;
	}
    else if (installResult == NativeAppFramework.RESULT_NET_TIMEOUT)
    {
		if( deletedFolder )
			DWfile.createFolder(sdkPath);
		alert( dw.loadString('NAF/configureAppFrameworks/installNeedsToBeOnline/alert') );
		return false;
    }
	
	if( !validateAndroidSDK(sdkPath) )
	{
		dwscripts.debugAlert("Install passed but Validate failed!!!" );
		alert( dw.loadString('NAF/configureAppFrameworks/installAndroidSDKFailed/alert') );
		return false;
	}
	
	//turn on the install success field
	document.getElementById("androidInstallText").style.display = "none";
	document.getElementById("androidSDKInstalledSuccess").style.display = "";
	document.getElementById("androidSDKInstalledSuccess").style.color = "green";
	
	return true;
}

//--------------------------------------------------------------------
// FUNCTION:
//   addSeperatorAsNeeded()
//
// DESCRIPTION:
//  check the path of a URI and insure it ends in a seperator
//
// ARGUMENTS: 
//   inURI - the URI to check
//
// RETURNS:
//   modified URI which ends in a seperator.
//--------------------------------------------------------------------
function addSeperatorAsNeeded(inURI)
{
    var returnVal = inURI;

    var pathStr = returnVal.getPath();
    if (pathStr.substr(pathStr.length - 1, 1) != "/")
    {
        pathStr = pathStr + "/";
        returnVal.setPath(pathStr);
    }
    return returnVal;
}

