var functionOnCloseDiv  = "";

function createButtonPopup(tsi_button, removeOnClick, title, functionOnClose, doNotClose) {

	var layer = document.getElementById("semiTransparentLayer");
	var div = null;
	var div4Message = null;
    
	if (arguments.length < 4) {
	    doNotClose = false;
	}

	if (arguments.length > 3) {
		functionOnCloseDiv = functionOnClose;
	}
	else {
		functionOnCloseDiv = "";
	}
	
	if (layer == null) {
		var height2 = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
		var width2 = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
		var height = screen.height > height2 ? screen.height : height2;
		var width = screen.width > width2 ? screen.width : width2;
		

		var linkImage = document.getElementById(tsi_button);
		if(linkImage != null)
			linkImagePosition = findPos(linkImage);
		ChangeSelectBoxVisibility("hidden");

		//semi-transparent div to lie on top of the entire page.
		layer = document.createElement('div');
		layer.id = 'semiTransparentLayer';
		layer.className = "PopupDivBackground";
		layer.style.height = (height * 5) + 'px';
		layer.style.width = (width * 5) + 'px';
		layer.style.height = '100%';
		layer.style.width = '100%';	
		if (removeOnClick)
		{
			layer.onclick = function() {
				document.body.removeChild(document.getElementById('semiTransparentLayer'));
				document.body.removeChild(document.getElementById('popUpDivFromButton'));
				ChangeSelectBoxVisibility("visible");
				tryFunctionOnClose();
			};
		}
		document.body.appendChild(layer);
	
		

		//div on top of the semi-transparent layer.
		div = document.createElement('div');
		div.id = "popUpDivFromButton";
		if(linkImage != null)
		{
			div.style.top = linkImagePosition[0] + linkImage.offsetHeight - 1;
			div.style.left = linkImagePosition[1] - 2;
		}
		div.className = "PopupDiv";
		div.style.display = "none";
		document.body.appendChild(div);
		var tbl = document.createElement("table");
		tbl.id = "popupHeadingTable"
		div.appendChild(tbl);
		
		var tblBody = document.createElement("tbody");
		tbl.appendChild(tblBody);
		var row = document.createElement("tr");
		tblBody.appendChild(row);
		var cell1 = document.createElement("td");
		var cell2 = document.createElement("td");
		row.appendChild(cell1);
		row.appendChild(cell2);
		//add title heading
		var message = document.createElement('div');
		message.style.styleFloat = 'left';
		message.style.cssFloat = 'left';
		message.className = 'redHeader';
		message.innerHTML = toLowerCaseExceptFirstCharacter(title);
		cell1.appendChild(message);


		cell2.style.textAlign = 'right';
		cell2.style.verticalAlign = 'top';
		if (!doNotClose) {
		    var xClose = document.createElement('img');
		    xClose.src = "/Images/Buttons/KNOTIA/Button_X_GreyBG.gif"
		    xClose.style.cursor = 'pointer';
		    xClose.onclick = function () {
		        removeButtonPopup();
		    };
		    cell2.appendChild(xClose);
		}
		div.appendChild(document.createElement('br'));
		div4Message = document.createElement('div');
		div4Message.className = "PopupDivBody";
		div.appendChild(div4Message);
		if(linkImage != null)
			$(div).slideDown("fast");
	}
	//after div is fully created set the new table width
	setTimeout("fixTableWidth()",1);
	setTimeout("check4rightAlign('" + tsi_button + "')",2);

	return div4Message;
}

function check4rightAlign(tsi_button)
{
	if(tsi_button != ""){
		var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
		var popup = document.getElementById("popUpDivFromButton");
		if(width < parseInt(popup.style.left) + $(popup).outerWidth(false))
		{	
			//if its not already on the left hand of the window
			if(width/2 < parseInt(popup.style.left))
			{
				buttonToGoUnder = document.getElementById(tsi_button);
				if(buttonToGoUnder!=null)
				{
					linkUnderPos = findPos(buttonToGoUnder);
					popup.style.left = (linkUnderPos[1] + $(buttonToGoUnder).outerWidth(false) - $(popup).outerWidth(false)) + 'px';
					
				}
			}
		}
	}
}

function fixTableWidth()
{
	if(document.getElementById("popupHeadingTable")==null)
	 return;

	if($("#popupHeadingTable").width() > $("#popUpDivFromButton").width() - 20)
	{
		$("#popupHeadingTable").width($("#popUpDivFromButton").width() + 20)
	}
	else
	{
		$("#popupHeadingTable").width($("#popUpDivFromButton").width())
	}
}


function removeButtonPopup() {
	if (document.getElementById('semiTransparentLayer') != null) {
		//stop embeded media player before closing
		if(document.getElementById('popUpDivFromButton').innerHTML.indexOf('MediaPlayer') != -1)
		{
			MediaPlayer.stop();
		}
		document.body.removeChild(document.getElementById('semiTransparentLayer'));
		document.body.removeChild(document.getElementById('popUpDivFromButton'));
		ChangeSelectBoxVisibility("visible");
		tryFunctionOnClose();
	}
}

//function to create a div that is centred in the page
function createCenteredPopupDiv(innerHTML, removeOnClick, title, functionOnClose, doNotClose) {
    var div = null;

	if (arguments.length > 3) {
		div = createButtonPopup("", removeOnClick, title, functionOnClose, doNotClose);
	}
	else {
		div = createButtonPopup("", removeOnClick, title);
	}
	
	if(div==null)
		return null;

	div.innerHTML = innerHTML;
	
	var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
	var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;

	var centreDiv = document.getElementById('popUpDivFromButton');

	centreDiv.style.top = parseInt(parseInt(height)/2 - parseInt($(centreDiv).height())/2) + 'px';
	centreDiv.style.top = (parseInt(centreDiv.style.top) > 0 ? parseInt(centreDiv.style.top) : 0) + 'px';
	centreDiv.style.left = parseInt(parseInt(width)/2 - parseInt($(centreDiv).width())/2) + 'px';
	centreDiv.style.left = (parseInt(centreDiv.style.left) > 0 ? parseInt(centreDiv.style.left) : 0) + 'px';
	//centreDiv.style.maxWidth = width - parseInt(centreDiv.style.left);
	//centreDiv.style.maxHeight = height - parseInt(centreDiv.style.top);	
	
	
	$(centreDiv).slideDown("fast");

	
	return div;
}

//function to try an on close function after div closes
function tryFunctionOnClose()
{
	if(functionOnCloseDiv.length > 0)
	{
		try
		{
			eval(functionOnCloseDiv);
		}
		catch(Err) {
		//do nothing
		}
	}
}

//function to get any element postion
function findPos(obj) {
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curtop, curleft];
}


//fix safari and chrome padding problem
function paddingFix4Safari() {
    //no longer need to run this since we are using a doctype
	if(jQuery)
	{
	    $(document).ready(function () {
			paddingFix();
		});
	}
	else {
		paddingFix();
	}
}


function paddingFix4Element(sElemId) {
    //no longer need to run this since we are using a doctype
    try {

        var objElement = document.getElementById(sElemId);
        //check if its safari/iphone to run the padding fix
        if (navigator.userAgent.toLowerCase().indexOf('playbook') != -1 || (navigator.userAgent.toLowerCase().indexOf('ipad') != -1 && (navigator.userAgent.toLowerCase().indexOf('cpu os 4') != -1 || navigator.userAgent.toLowerCase().indexOf('cpu os 3') != -1))) {
            //check if it has already been applied
            if (document.getElementById("lstElementsFixed").value.indexOf(sElemId) == -1) {
                document.getElementById("lstElementsFixed").value += sElemId + ",";

                var iDifference = objElement.offsetWidth - $("#" + sElemId).width();
                objElement.style.width = objElement.offsetWidth - iDifference - iDifference;            
            }
            
        }
    }
    catch (Error) {
        
    }

}



function paddingFix() {
    //check if its playbook/old ipad to run the padding fix
    if (navigator.userAgent.toLowerCase().indexOf('playbook') != -1 || (navigator.userAgent.toLowerCase().indexOf('ipad') != -1 && (navigator.userAgent.toLowerCase().indexOf('cpu os 4') != -1 || navigator.userAgent.toLowerCase().indexOf('cpu os 3') != -1))) {
        
		for(var i = 0; i<document.styleSheets.length; i++){
			var mysheet=document.styleSheets[i];
			var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules;
			for(var j =0; j<myrules.length; j++){
				if (!isNaN(parseInt(myrules[j].style.height)) && myrules[j].style.height.indexOf('px')>0)
				{
					if(parseInt(myrules[j].style.paddingBottom) > 0 && !isNaN(parseInt(myrules[j].style.paddingBottom)))
					{
						myrules[j].style.height = (parseInt(myrules[j].style.height) - parseInt(myrules[j].style.paddingBottom)) + 'px';
					}
					if(parseInt(myrules[j].style.paddingTop) > 0 && !isNaN(parseInt(myrules[j].style.paddingTop)))
					{
						myrules[j].style.height = (parseInt(myrules[j].style.height) - parseInt(myrules[j].style.paddingTop)) + 'px';
					}	
				}
				if (!isNaN(parseInt(myrules[j].style.width)) && myrules[j].style.width.indexOf('px')>0)
				{
					if(parseInt(myrules[j].style.paddingLeft) > 0 && !isNaN(parseInt(myrules[j].style.paddingLeft)))
					{
						myrules[j].style.width = (parseInt(myrules[j].style.width) - parseInt(myrules[j].style.paddingLeft)) + 'px';
					}
					if(parseInt(myrules[j].style.paddingRight) > 0 && !isNaN(parseInt(myrules[j].style.paddingRight)))
					{
						myrules[j].style.width = (parseInt(myrules[j].style.width) - parseInt(myrules[j].style.paddingRight)) + 'px';
					}	
				}
			}
		}
	}
}

//fix safari and chrome padding problem
function documentBodyFix4Safari() {
    if (jQuery) {
        $(document).ready(function () {
            documentBodyFix();
        });
    }
    else {
        documentBodyFix();
    }
}

function documentBodyFix() {
    //check if its playbook/old ipad to run the padding fix
    if (navigator.userAgent.toLowerCase().indexOf('playbook') != -1 || (navigator.userAgent.toLowerCase().indexOf('ipad') != -1 && (navigator.userAgent.toLowerCase().indexOf('cpu os 4') != -1 || navigator.userAgent.toLowerCase().indexOf('cpu os 3') != -1))) {
        var divDocumentBodyContext = document.getElementById("divDocumentBodyContext");
        if (divDocumentBodyContext != null) // <- this only exists in briefcase.aspx and home.aspx
        {
            $(divDocumentBodyContext).width(parseInt($(divDocumentBodyContext).width()) - Math.max(10, parseInt($(divDocumentBodyContext).css("padding-left"))) - Math.max(10, parseInt($(divDocumentBodyContext).css("padding-right"))) - 10);
           // $(divDocumentBodyContext).height(parseInt($(divDocumentBodyContext).height())  - 4);
            var divDocumentBody = document.getElementById("divDocumentBody");
            $(divDocumentBody).width(parseInt($(divDocumentBody).width()) - Math.max(10, parseInt($(divDocumentBody).css("padding-left"))) - Math.max(10, parseInt($(divDocumentBody).css("padding-right"))) - 3);
        }
    }
}

function GetString(stringName) {
	if (stringName.length > 0 && isDefined("GlobalStrings." + stringName)) {
		return eval("GlobalStrings." + stringName);
	}
	else {
		return "N/A";
	}
}



function UnDecodeHTMLCharacters(strValueToDecode)
{	
	if (!strValueToDecode){
		return "";
	}
	if (strValueToDecode.length == 0){
		return "";
	}

	var objTA = document.createElement("textarea");

	strValueToDecode = strValueToDecode.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&amp;#/gi,"&#");
	objTA.innerHTML = strValueToDecode;

	return objTA.value;
}

var dynamicLoading = 0;

function parseAjaxResponse(sThisReqStatusCode, sThisReqResponseText)
{
	try
	{
		var oResponse = eval("(" + sThisReqResponseText + ")");
	}
	catch (exc)
	{
		var sTestText = sThisReqResponseText.toLowerCase();
		if (
			(sTestText.indexOf("form id=\"floginhidden\"") >= 0)
			||
			(sThisReqStatusCode == 0 && sTestText.length == 0)
			)
		{
			var reTwoSlash = new RegExp("//");
			var sLocation = window.location.toString();
			var i = sLocation.replace(reTwoSlash, "").indexOf("/") + 2;
			var sReturnUrl = sLocation.substr(i);
			window.location.replace("/Login/Login.aspx?ReturnUrl=" + escape(sReturnUrl));
			return (null);
		}
	}
	return (oResponse);
}

function toLowerCaseExceptFirstCharacter(strToFix) {
    if (typeof strToFix == 'string' && strToFix.length > 1) {
        if (strToFix.length == 1) {
            return strToFix.toUpperCase();
        }
        else {
            return strToFix.substring(0, 1).toUpperCase() + strToFix.substring(1, strToFix.length).toLowerCase();
        }
    }
    else {
        return strToFix;
    }
}


function imgTextMouseOver(strBaseID) {
    var imgName = '#img' + strBaseID;
    var src = $(imgName).attr("src").replace("_UP.gif", "_OVR.gif");
    $(imgName).attr("src", src);

    var txtName = '#txt' + strBaseID;
    $(txtName).css("text-decoration", "underline");

}

function imgTextMouseOut(strBaseID) {
    var sName = '#img' + strBaseID;
    var src = $(sName).attr("src").replace("_OVR.gif", "_UP.gif");
    $(sName).attr("src", src);

    var txtName = '#txt' + strBaseID;
    $(txtName).css("text-decoration", "none");
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'), with_this);
}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.substring(0,index) + temp.substring(index).replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind, index + stringToReplace.length);
    }
    return temp;
}


function js_resolveURL(path) {
    return path.replace("~/", glb_ResolveUrlJs_Base);
}
