﻿/// <summary>
/// utility functions
/// </summary>
///
/// <remarks>
/// <CodeWalkthroughHistory>
/// Reviewed By				Date Reviewed		Checklist Status
/// </CodeWalkthroughHistory> 
/// <RevisionHistory>
/// Author					Date				Description
/// Sergey Starikov	01/01/2008	
/// </RevisionHistory>
/// </remarks>

function getArchivesExt() {
	return ".zip";
}

function isArchivesExt(ext) {
	return ext == getArchivesExt();
}

var maxFileSizeVar = 2147483648 // 2 GB
function getMaxFileSize()
{
	return maxFileSizeVar;
}

var userProfile = null;

function getUserProfile()
{
	if(userProfile == null){
		var commonService = new CommonService();
		userProfile = commonService.getUserProfile();
	}
	return userProfile;
}

function getQoutaLimit(path)
{
	var userProfile  = getUserProfile();
	var qoutaVal ;
	
	if(userProfile==null)
		return true;

	var root = getRootPath(path);
	for(var i=0, len = userProfile.allUserRootFolders.length;i<len;i++)
	{
		if(userProfile.allUserRootFolders[i].virtualPath == root)
		{
			var rootFolder = userProfile.allUserRootFolders[i];
			var qouta = rootFolder.pathPermission.quotaLimit
			
			qoutaVal = formatBytes(qouta);
			
			break;
		}
	}
	
	return qoutaVal;
}

function isAllowedPermission(path, permission)
{
	var userProfile  = getUserProfile();

	if(userProfile==null)
		return true;
		
	var root = getRootPath(path);
	for(var i=0, len = userProfile.allUserRootFolders.length;i<len;i++)
	{
		if(userProfile.allUserRootFolders[i].virtualPath == root)
		{
			var rootFolder = userProfile.allUserRootFolders[i];
			for(var j=0, len = rootFolder.pathPermission.permissions.length;j<len;j++)
			{
				var perm = rootFolder.pathPermission.permissions[j];
				if(perm.permissionInfo.name == permission)
				{
					return perm.isSet; 
				}
			}
			break;
		}
	}
	return false;
}

function isAllowedCopy(path)
{
	return isAllowedPermission(path, 'Copy');
}

function isAllowedCut(path)
{
	return isAllowedPermission(path, 'Cut');
}

function isAllowedPaste(path)
{
	return isAllowedPermission(path, 'Paste');
}

function isAllowedCreate(path)
{
	return isAllowedPermission(path, 'Create');
}

function isAllowedDelete(path)
{
	return isAllowedPermission(path, 'Delete');
}

function isAllowedRename(path)
{
	return isAllowedPermission(path, 'Delete') || isAllowedPermission(path, 'Create') ;
}

function isAllowedMove(path)
{
	return isAllowedPermission(path, 'Delete');
}

function isAllowedCompressExtract(path)
{
	return isAllowedPermission(path, 'CompressExtract');
}

function isAllowedUpload(path)
{
	return isAllowedPermission(path, 'Upload');
}

function isAllowedDownload(path)
{
	return isAllowedPermission(path, 'Download');
}

function reloginUser() {
	var loginService = new LoginService();
	var result = loginService.relogin();
	return result;
}

function logout()
{
	loginService  = new LoginService();
	result = loginService.logout();
	window.location = "login.aspx";
}

function managerLoad()
{
	var commonService = new CommonService();
	userProfile = commonService.getUserProfile();
	
	checkIfLogged();
	
	this.logCount = 0;
	
	if(userProfile !=null && userProfile.user.userMustChangePassword == true)
	{
		UserChangePasswordDialog(this, userProfile, function()
		{
			this.logCount++;
			userProfile = commonService.getUserProfile();
			if(userProfile.user.userMustChangePassword == true)
			{
				if(count == 3)
					logout();
				else
					managerLoad();
			}
		});
	}
}

function checkIfLogged() {
	var commonService = new CommonService();
	if (commonService.isSessionExpired()){
		Ext.Msg.alert("Message", "Session is expired!");
		logout();
	}
}

function ping() {
	var commonService = new CommonService();
	commonService.ping();
}

function getServerFileUrl(path )
{
	var commonService = new CommonService();
	return commonService.getFileUrl(path);	
//	serverUrl = Solverlabs.ASPXFileManager.WebServices.FileBrowserService.GetFileUrl(path);
//	return serverUrl;
}


function isArray(obj) {
//returns true is it is an array
  if (obj.constructor.toString().indexOf("Array") == -1)
    return false;
  else
    return true;
}

function isRootNode(node) {
	if(node.parentNode!=null && node.parentNode!=undefined)
		return node.parentNode.id == 'GROOT';
	return false
}

function getRootPath(path) {
//returns true is it is an array
	var p = path;
	var rootPath = p.substring(0, p.indexOf('\\')+1);
	
	if(rootPath.length > 0 && rootPath.lastIndexOf('\\')==-1)
		rootPath += '\\';
	return rootPath;
}


function getParentPath(path) {
//returns true is it is an array
	var p = path;
	if(p.lastIndexOf('\\')==p.length -1)
	{
		p=p.substr(0, p.length-1);
	}
	var parentPath = p.substring(0,p.lastIndexOf('\\'));
	
	if(parentPath.length > 0 && parentPath.lastIndexOf('\\')==-1)
		parentPath += '\\';
	return parentPath;
}

function getItemName(path) {
	var p = path;
	if(p.lastIndexOf('\\')==p.length -1)
	{
		p=p.substr(0, p.length-1);
	}
	return p.substring(p.lastIndexOf('\\')+1);
}

function getItemNameWithoutExt(path) {
	var name = getItemName(path);
	var idx = name.lastIndexOf('.');
	if (idx > 0) {
		var p = name.substr(0, idx);
		return p;
	} else {
		return name;
	}
}

function concatPath(path, item) {
//returns true is it is an array
	if(path.lastIndexOf('\\')==path.length -1)
	{
		return path + item;
	}
	else
		return path + '\\' + item;
}


function getFilesize(element)
{
		var oas = new ActiveXObject("Scripting.FileSystemObject");
		//var d = document.forms[0].FileUpload.value;
		var d = element.value;
		var e = oas.getFile(d);
		var f = e.size;
		
		//alert(f + " bytes");
		alert("Name: " + e.name);
		alert("Size: " + e.size);
		alert("Type: " + e.type);
			
		return f;
}


	/**
	 * Formats raw bytes into kB/mB/GB/TB
	 * @param {Integer} bytes
	 * @return {String}
	 */
	function QoutaValue(val, unit)
	{
		this.value = val; 
		this.unit = unit;
	}
	
	function formatBytes(bytes) {
			if(isNaN(bytes)) {	return new QoutaValue(0, ''); }
	
			var unit, val;
	
			if(bytes < 999)	{
				unit = 'B';
				val = bytes;
			}	else if(bytes < 999999)	{
				unit = 'KB';
				val = Math.round(bytes/1000);
			}	else if(bytes < 999999999)	{
				unit = 'MB';
				val = Math.round(bytes/100000) / 10;
			}	else if(bytes < 999999999999)	{
				unit = 'GB';
				val = Math.round(bytes/100000000) / 10;
			}	else	{
				unit = 'TB';
				val = Math.round(bytes/100000000000) / 10;
			}
	
			return new QoutaValue(val, unit);
		}

		function formatSize(bytes) {
			if (bytes == null || bytes == undefined || bytes == "")
				return "";

			var unit, val;
	
			if(bytes < 999)	{
				unit = 'B';
				val = bytes;
			}	else if(bytes < 999999)	{
				unit = 'KB';
				val = Math.round(bytes / 1000 ) ;
			}	else if(bytes < 999999999)	{
				unit = 'MB';
				val = (Math.round(bytes / 10000 ) / 100) ;
			}	else if(bytes < 999999999999)	{
				unit = 'GB';
				val = (Math.round(bytes / 10000000 ) / 100) ;
			}	else	{
				unit = 'TB';
				val = (Math.round(bytes / 10000000000 ) / 100) ;
			}
			
			return val + " " + unit;
		}
		
	function formatToBytes(data) {
			if(isNaN(data.value)) {	return (0); }
			
			var unit, val;
			
			if(data.unit == 'B')
			{
				val = data.value;
			}
			else if (data.unit == 'KB')
			{
				val = data.value*1000;
			}
			else if (data.unit == 'MB')
			{
				val = data.value*1000*1000;
			}
			else if (data.unit == 'GB')
			{
				val = data.value*1000*1000*1000;
			}
			else if (data.unit == 'TB')
			{
				val = data.value*1000*1000*1000*1000;
			}
			
			return val;
		}



// Add the additional 'advanced' VTypes
		Ext.apply(Ext.form.VTypes, {
			daterange: function(val, field) {
				var date = field.parseDate(val);

				// We need to force the picker to update values to recaluate the disabled dates display
				var dispUpd = function(picker) {
					var ad = picker.activeDate;
					picker.activeDate = null;
					picker.update(ad);
				};

				if (field.startDateField) {
					var sd = Ext.getCmp(field.startDateField);
					if (sd) {
						sd.maxValue = date;
						if (sd.menu && sd.menu.picker) {
							sd.menu.picker.maxDate = date;
							dispUpd(sd.menu.picker);
						}
					}
				} else if (field.endDateField) {
					var ed = Ext.getCmp(field.endDateField);
					if (ed) {
						ed.minValue = date;
						if (ed.menu && ed.menu.picker) {
							ed.menu.picker.minDate = date;
							dispUpd(ed.menu.picker);
						}
					}
				}
				/* Always return true since we're only using this vtype
				* to set the min/max allowed values (these are tested
				* for after the vtype test)
				*/
				return true;
			}
  ,

			password: function(val, field) {
				if (field.initialPassField) {
					var pwd = Ext.getCmp(field.initialPassField);
					return (val == pwd.getValue());
				}
				return true;
			},

			passwordText: 'Passwords do not match'
			
			
	 ,password2: function(value, field)
   {
      if (field.initialPasswordField)
      {
         var pwd = Ext.getCmp(field.initialPasswordField);
         this.passwordText = "Confirmation does not match your intial password entry.";
         return (value == pwd.getValue());
      }
 
      this.passwordText = "Passwords must be at least 5 characters, containing either a number, or a valid special character (!@#$%^&*()-_=+)";
 
      var hasSpecial = value.match(/[0-9!@#\$%\^&\*\(\)\-_=\+]+/i);
      var hasLength = (value.length >= 5);
 
      return (hasSpecial && hasLength);
   }
 
//	   passwordText: ‘Passwords must be at least 5 characters, containing either a number, or a valid special character (!@#$%^&*()-_=+)’,

	 , fullnameValidator: function(value, field) {
   
	   	var passValue = TrimString(value);
		 	
      return passValue.length  >0;
   }
			
		});

function TrimString(sInString){
	sInString = sInString.replace(/ /g," ");
	return sInString.replace(/(^\s+)|(\s+$)/g, "");
}


function IsOwerWrite(path, callback)
{
	var title = "Question";
	var reallyWantText = 'Do you really want to';
	var overightText = "overwrite"
	var  msg =  reallyWantText + ' ' + overightText + ' <b>' + getItemName(path) + '</b>?'
	
  Ext.MessageBox.confirm('Confirm', msg, function(response) {
					// do nothing if answer is not yes
					if ('yes' !== response) {
						callback(true);
						return;
					}else
						callback(false);
				});
/*
			Ext.Msg.show({
				title: title
			, msg: reallyWantText + ' ' + overightText + ' <b>' + getItemName(path) + '</b>?'
			, icon: Ext.Msg.WARNING
			, buttons: Ext.Msg.YESNO
			, scope: this
			, fn: function(response) {
					// do nothing if answer is not yes
					if ('yes' !== response) {
						callback(true);
						return;
					}else
						callback(false);
				}
			});
*/
}
