function GetWebByFullUrl($url)
{
	$web = Get-SPWeb $url -ErrorAction:SilentlyContinue
	if (!$web)
	{
		$lastSlashPos = $url.LastIndexOf("/");
		if ($lastSlashPos -gt 0)
		{			
			$subUrl = $url.Substring(0, $lastSlashPos);
			return GetWebByUrl($subUrl)
		}
	}

	return $web
}

function GetWebUrlByFullUrl($url)
{
	$web = Get-SPWeb $url -ErrorAction:SilentlyContinue
	if (!$web)
	{
		$lastSlashPos = $url.LastIndexOf("/");
		if ($lastSlashPos -gt 0)
		{			
			$subUrl = $url.Substring(0, $lastSlashPos);
			return GetWebUrlByFullUrl($subUrl)
		}
	}
	else
	{
		return $url
	}

	return $null
}

function GetWebUrlByFullUrlWithNotification($pageUrl)
{
	$webUrl = GetWebUrlByFullUrl($pageUrl)
	if (!$webUrl)
	{
		Write-Host $($MSG_MISSING_WEB -f $sourcePageUrl) -ForegroundColor Red
		Write-Host $MSG_OPERATION_TERMINATED -ForegroundColor Red
		exit
	}
	return $webUrl
}

function CreateTeamSite($baseUrl, $newSiteUrl, $name, $AddToQuickLaunch, $AddToTopNav, $UseParentTopNav, $UniquePermissions)
{
   return CreateSite $baseUrl $newSiteUrl $name "STS#0" $AddToQuickLaunch $AddToTopNav $UseParentTopNav $UniquePermissions
}

function CreateBlankSite($baseUrl, $newSiteUrl, $name, $AddToQuickLaunch, $AddToTopNav, $UseParentTopNav, $UniquePermissions)
{
    return CreateSite $baseUrl $newSiteUrl $name "STS#1" $AddToQuickLaunch $AddToTopNav $UseParentTopNav $UniquePermissions
}

function CreateSite($baseUrl, $newSiteUrl, $name, $template, $AddToQuickLaunch, $AddToTopNav, $UseParentTopNav, $UniquePermissions)
{
    Write-Host "Creating site " $name -ForegroundColor: Yellow
	$url = Join-Parts ($baseUrl,$newSiteUrl) '/' 
	Write-Host  $url
	$newWeb = New-SPWeb -Url  $url -AddToQuickLaunch: $AddToQuickLaunch -UniquePermissions: $UniquePermissions -AddToTopNav: $AddToTopNav  -Name "$name" -Template "$template" -UseParentTopNav:$UseParentTopNav -Confirm:$false -ErrorAction Stop -Language 1049
    #$newWeb = New-SPWeb -Url "$baseUrl/$newSiteUrl" -AddToQuickLaunch: $AddToQuickLaunch -UniquePermissions: $UniquePermissions -AddToTopNav: $AddToTopNav  -Name "$name" -Template "$template" -UseParentTopNav:$UseParentTopNav -Confirm:$false -ErrorAction Stop
    Write-Host "Site " $url " created"
    return $newWeb
}

function RemoveSite($url)
{
    $exists = (Get-SPWeb $url -ErrorAction SilentlyContinue) -ne $null
    if($exists)
    {
        Write-Host "Removing site " $url
        Remove-SPWeb $url -Confirm:$false -ErrorAction Stop
        Write-Host "Site " $url " removed"
    }
    else
    {
        Write-Host "Site " $url " not found" -ForegroundColor Yellow
    }
}

function Join-Parts {
    param ([string[]] $Parts, [string] $Seperator = '')
    $search = '(?<!:)' + [regex]::Escape($Seperator) + '+'  #Replace multiples except in front of a colon for URLs.
    $replace = $Seperator
    ($Parts | ? {$_ -and $_.Trim().Length}) -join $Seperator -replace $search, $replace
}
