﻿var DMWIN_KEY = "DMWin";
var regex_FindDMWin = /DMWin=[0-9a-fA-F\-]*/g;

function sendWindowName() {
	if (top.window.location.href.toLowerCase().indexOf("multitab.aspx") == -1) {
		if (window.location.href.match(regex_FindDMWin))
			navigateWindow(window, multiTabPageUrl);
		else if (top.window.name == "")
			navigateWindow(window, multiTabPageUrl);
		else if (top.window.name != "")
			navigateWindow(window, generateUrl());
	}
}

function generateUrl() {
	var currentUrl = window.location.href.replace(/dmwin/i, DMWIN_KEY);
	var q = queryString(DMWIN_KEY);
	if (q != null && q.length > 0)
		currentUrl = currentUrl.replace(DMWIN_KEY + "=" + q, DMWIN_KEY + "=" + top.window.name);
	else
		currentUrl = window.location.href + (window.location.search.length > 0 ? "&" : "?") + DMWIN_KEY + "=" + top.window.name;
	return currentUrl;
}

function queryString(key) {
	var re = new RegExp("[?&]" + key + "=([^&$]*)", "i");
	var offset = location.search.search(re);
	if (offset == -1) return null;
	return RegExp.$1;
}

function isIgnoredPage(pathname) {
	if (ignoredPages) {
		for (var i = 0; i < ignoredPages.length; i++) {
			if (pathname.toLowerCase().indexOf(ignoredPages[i].toLowerCase()) > -1)
				return true;
		}

	}

	return false;
}

function checkWindowName(url) {
	if (isIgnoredPage(top.window.location.pathname))
		return;

	if (top.window.name != DMWin)
		navigateWindow(top.window, url);

}

function navigateWindow(targetWindow, url) {
	// this if statement was added to mitigate
	// enless redirects to the same location
	// caused in some instances where checkWindowName
	// calls this method multiple times.
	if (window.name == "" && targetWindow.location.href != url) {
		targetWindow.location.href = url;
	}
	else if (window.name != "")
		targetWindow.location.href = url;
}

$(document).ready(function() {
	$("iframe").each(function() { this.name = window.name; });
	$("a[href]").each(function() {
		if (this.href && this.href.indexOf("DMWin") == -1 && this.hostname == this.ownerDocument.domain) {
			if (this.href.indexOf("?") > -1)
				this.href = this.href + "&DMWin=" + window.name;
			else
				this.href = this.href + "?DMWin=" + window.name;
		}
	});
});

