// shared with SiteCommon/javascript/AjaxPostBack.js
var BvdPageDisplayProgressCursor = true;
var BvdPageResetProgressCursor = false;
var RefreshPageDelegate = null;

function DefineBvDPostBack()
{
	if (typeof(__doPostBack)=='function' && typeof(__oldPostBack) == 'undefined')
	{
		var __orgPostBack = __doPostBack;
		__doPostBack = function(eventTarget, eventArgument) 
		{
			if (BvdPageDisplayProgressCursor)
				document.body.style.cursor = "progress";

			__orgPostBack(eventTarget, eventArgument);
			
			if (BvdPageResetProgressCursor === true)
			{
			    document.body.style.cursor = "auto";
			    BvdPageResetProgressCursor = false;
			}

	        BvdPageDisplayProgressCursor = true;
		}
	}
}

function RegisterBeforePostBackEvent(func)
{
    if (typeof(__doPostBack)=='function')
	{
		var __orgPostBack = __doPostBack;
		__doPostBack = function(eventTarget, eventArgument) 
		{
		    func();
			__orgPostBack(eventTarget, eventArgument);
		}
	}
}

function ResetCursor()
{
    BvdPageResetProgressCursor = true;
    return true;
}

// Refresh the page by performing a post-back.
// If a specific refresh must be performed (for ajax management for example), 
// you can initialize the RefreshPageDelegate.
function RefreshPage()
{
	if(RefreshPageDelegate != null)
		RefreshPageDelegate();
	else
		__doPostBack("", "");
}

/* Correct PNG */

var m_IsPNGCorrectionNeeded = null;

function IsPNGCorrectionNeeded()
{
	if (m_IsPNGCorrectionNeeded == null)
	{
		var arVersion = navigator.appVersion.split("MSIE");
		var version = parseFloat(arVersion[1]);

		try
		{
			m_IsPNGCorrectionNeeded = (version >= 5.5 && version < 7 && (document.body.filters != null));
		}
		catch(e)
		{
			m_IsPNGCorrectionNeeded = false; // because document.body.filters doesn't exist
		}
   }
   
   return m_IsPNGCorrectionNeeded;
}

function IsPNG(image)
{
	var src = image.src;

	if (src == null || src.length == 0)
		return false;

	return (src.substr(src.length-3, 3).toUpperCase() == "PNG");
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 and 6.
{
   if (!IsPNGCorrectionNeeded()) 
		return;
	
	correctItems(document.images);
	correctItems(document.getElementsByTagName("input"));
	
	function correctItems(items)
	{
		var n=items.length;
		for(var i=0; i<n; i++)
		{
			var item = items[i];
			if (IsPNG(item))
				correctPNGImage(item);
		}
	}
}

function correctPNGImage(img)
{
	if (img.style.filter.length != 0)
		return;

	var w = img.offsetWidth;
	var h = img.offsetHeight;
	if (w == 0 || h == 0)
	{
		w = img.currentStyle.width;
		h = img.currentStyle.height;
		
		if (w == 0 || h == 0)
		{
			if (NeedsPngWarning)
			{
				if (!JsDebug)
					return;
				alert("Please specify a width/height for all png images. All such images have been surrounded in red");
				NeedsPngWarning = false;
			}
			img.style.border="solid red 1px";
			return;
		}
	}

	img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src + "', sizingMethod='scale')";
	img.src = "common/Icons/transdot.gif";
	img.style.width = w;
	img.style.height = h;
}
var NeedsPngWarning = true;

function correctImage(img)
{
	if (!IsPNGCorrectionNeeded()) 
		return;
		
	if (IsPNG(img))
		correctPNGImage(img);
}

function getTranslation (msg)
{
	if (JSTranslations[msg] != null)
		return JSTranslations[msg];
	else
		return msg;
}

/* Disable ViewSource */ 

function DisableViewSource_HidePopup(e)
{
	var srcElement = e != null ? e.target : window.event.srcElement;
	
	if(srcElement != null && srcElement.tagName != "INPUT" && srcElement.tagName != "TEXTAREA")
	{		
		alert("Copyright (c) " + new Date().getFullYear() + " Bureau van Dijk");
		return false;
	}
}

function DisableViewSource_FireFox(evt)
{
  if (evt == null)
    evt = window.event;

  // Check point against client area	
  var clientWidth = document.body.clientWidth;
  var clientHeight = document.body.clientHeight;
  if (evt.clientX >= clientWidth || evt.clientY >= clientHeight)
	return true;
	    
	if (evt == null)
	{
		ShowViewSourceAlert();
		return false;
    }		    

    var srcElement = navigator.userAgent.indexOf("MSIE") >=0 ? evt.srcElement : evt.target;
    if (srcElement == null)
		return true;
		
	if(srcElement.style.overflow == "auto" || srcElement.style.overflowY == "auto" || srcElement.style.overflowX == "auto")
		return true;

    if (HasMouseHandlers(srcElement))
		return true;
     
     DisableViewSource_HidePopup(evt);
     return false;
}

function HasMouseHandlers(_srcElement)
{
	var srcElement = _srcElement;
    var srcElementStr = "";
      
	do
	{
		srcElementStr = srcElement.tagName.toLowerCase();
		//alert(srcElementStr);		    
        if (srcElementStr == "a" || srcElementStr == "select" || srcElementStr == "input" || srcElementStr == "label" /*|| srcElementStr == "html"*/)
          return true;
          
        if (srcElement.onclick != null || srcElement.ondblclick != null || srcElement.onmousedown != null)
          return true;
          
        srcElement = srcElement.parentNode;
     } 
     while (srcElement != null && srcElementStr != "body" && srcElementStr != "html");
      
   return false;
}

function _np1()
{
	for(wi=0; wi<document.all.length; wi++)
   {
		if(document.all[wi].style.visibility!="hidden")
		{
			document.all[wi].style.visibility="hidden";
			document.all[wi].viewSourceMarker="gwp";
		}
	}
} 

function _np2()
{
	for (wi=0; wi<document.all.length; wi++)
	{
		if(document.all[wi].viewSourceMarker=="gwp")
			document.all[wi].style.visibility='';
	}
	DisableViewSource_HidePopup();
}

function DisableViewSourceStart()
{
	if(window.location.protocol.indexOf("file")!=-1)
		location="about&#058;blank";
		
	if(navigator.userAgent.indexOf("MSIE") >=0)
	{
		document.ondragstart = DisableViewSource_HidePopup;
		document.onselectstart = DisableViewSource_HidePopup;
	}
	else
	{
		document.onmousedown = DisableViewSource_FireFox;
	}
	
	document.oncontextmenu=DisableViewSource_HidePopup;
	
	window.onbeforeprint=_np1;
	window.onafterprint=_np2;
}

/* Client Resolution */

prevClientRes = null;

clientResTimeoutId = null;

function setClientResolutionToUrl(url)
{
	if (clientResTimeoutId != null)
		window.clearTimeout (clientResTimeoutId);

	clientResTimeoutId = window.setTimeout(setClientResolution, 500);
	
	function setClientResolution()
	{
		if (isPopUpWindow())
			return;

		// we dont send the client resolution to the server when the scrollbar is hidden (ModalLayerDialog)			
		if (document.body.style.overflow == "hidden")
			return;

		if (url == null || !url)
			return;
			
		var clientResolutionString = getClientResolutionString();
		if(clientResolutionString == "0x0") // In a iFrame for salesforce
		    return;
		if (clientResolutionString != prevClientRes)
		{
			(new Image).src = url + '&clientRes=' + clientResolutionString;
			prevClientRes = clientResolutionString;
		}
		
		clientResTimeoutId = null;
	}
}

function isPopUpWindow()
{
	if (!window.opener || window.opener == null)
	{
		try
		{
			if (!window.external || !window.external.dialogTop)
				return false;
		}
		catch(e)
		{
			return false;
		}
	}
	
	try
	{
		var tmp = window.opener.location.host;
	}
	catch(e)
	{
		return false;
	}
	return true;
}

function initClientResolutionScript()
{
	if (window.attachEvent)
		window.attachEvent("onresize",setClientResolutionHandler);
	else if(window.addEventListener) 
		window.addEventListener("resize",setClientResolutionHandler,false);
		
	setClientResolutionHandler();
}

function setClientResolutionToHiddenField(hiddenFieldName)
{
	var form = document.forms[0];
	
	if (form == null)
		return;

	var hiddenField = form[hiddenFieldName];
	
	if (hiddenField == null)
		return;
		
	var clientResolutionString = getClientResolutionString();
	
	if (clientResolutionString != prevClientRes)
	{
		hiddenField.value = clientResolutionString;
		prevClientRes = clientResolutionString;
	}
}

function getClientResolutionString()
{
	//thank VVD for this code
	var width=800;
	var height=600;

	if(window.innerWidth)
	{
		width=window.innerWidth;
		height=window.innerHeight;
	}
	else if(this.document.body)
	{
		width=this.document.body.clientWidth;
		height=this.document.body.clientHeight;
	}
	
	return width + "x" + height;
}

/* Javascript Profiling */

JSProfilingEnabled = false;

function InitJSProfiler()
{
	JSProfilingEnabled = true;
	m_JSProfiler = new JSProfiler();
}

function JSProfile(id)
{
	if (JSProfilingEnabled)
		m_JSProfiler.Profile(id);
}

function ProcessJSProfilerResult()
{
	if(typeof(m_JSProfiler) == "undefined")
		return;
	var trace = m_JSProfiler.GetTrace();

	if (trace.length > 0)
		alert(trace);
}

function JSProfiler()
{
	var m_TraceIDs = new Array();
	var m_Traces = new Array();
	var m_StartTime = null;
	var m_EndTime = null;
	
	this.Profile = function(id)
	{
		id = id.substr(0, 30);
		
		if (m_StartTime == null)
			m_StartTime = new Date();
	
		var trace = m_TraceIDs[id];
		
		if (trace == null)
		{
			trace = new Trace(id);
			m_TraceIDs[id] = trace;
			m_Traces.push(trace);
		}
	
		trace.Hit();
		m_EndTime = new Date();
	}
	
	var m_TotalTime = null;
	
	this.GetTotalTime = function()
	{
		if (m_TotalTime == null)
		{
			if (m_StartTime == null || m_EndTime == null)
				alert("GetTotalTime error");
				
			m_TotalTime = m_EndTime - m_StartTime;
		}
		
		return m_TotalTime;
	}
	
	this.SortTraces = function()
	{		
		m_Traces.sort(SortByTimeDesc);
		
		function SortByTimeDesc(a, b)
		{
			return (a.GetTime() > b.GetTime())? -1: 1;
		}
	}
	
	this.GetTrace = function()
	{
		var result = new StringBuilder();
		
		this.SortTraces();
		
		for(var i=0; i<m_Traces.length; i++)
		{
			var trace = m_Traces[i];
			
			result.append(Math.ceil(((trace.GetTime() * 100) / this.GetTotalTime())).toString());
			result.append("%\t(");
			result.append(trace.GetTime());
			result.append("ms)\t");
			result.append("hit: " + trace.GetHitCount() + "\t");
			result.append(": ");
			result.append(trace.GetLabel());
			
			result.append("\r\n");
		}
		
		return result.toString();
	}
	
	/* */
	
	function Trace(label)
	{
		var m_Label = label;
		var m_StartTime = null;
		var m_TotalTime = 0;
		var m_HitCount = 0;
		var m_HitOpened = false;
		
		this.Hit = function()
		{
			if (m_HitOpened)
			 {
				m_TotalTime += new Date() - m_StartTime;
			}
			else
			{
				m_HitCount++;
				m_StartTime = new Date();
			}
			
			m_HitOpened = !m_HitOpened;				
		}
		
		this.GetLabel = function()
		{
			return m_Label;
		}
		
		this.GetTime = function()
		{
			return m_TotalTime;
		}
		
		this.GetHitCount = function()
		{
			return m_HitCount;
		}
	}
	
	function StringBuilder()
	{
		var m_InnerArray = new Array();

		this.append = function(string)
		{
			m_InnerArray.push(string);
		}
		
		this.toString = function()
		{
			return m_InnerArray.join("");
		}
	}
}

// Post window.open
var postwindow = 
{
	FormAction:null,
	FormContent:null,
	OpenedWindows:{},
	open: function(query, postParams, windowName, windowParameters)
	{
		this.FormAction = query;
		this.FormContent = postParams;
		var newWindow = this.OpenedWindows[windowName];
		if (newWindow != null && !newWindow.closed && newWindow.location) 
			newWindow.location.replace("postwindow.html");
		else 
		{
			newWindow = window.open("postwindow.html", windowName, windowParameters);
			this.OpenedWindows[windowName] = newWindow;
		}
		if (newWindow && newWindow.focus )
			newWindow.focus();
		return newWindow;
	},
	submitForm:function(doc)
	{
		var form = doc.forms[0];
		form.action = this.FormAction;
		form.method="POST";
		var params = this.FormContent;
		for(var name in params)
		{
			var inputHiddenField = doc.createElement("INPUT");
			inputHiddenField.type = "hidden";
			inputHiddenField.id = name; 
			inputHiddenField.name = name; 
			inputHiddenField.value = params [name]; 
			form.appendChild(inputHiddenField);
		}
		form.submit();
	}
}

$.logBrowserStatistics = function(call)
{
    $.post(call, {'screenX':screen.width,'screenY':screen.height});
};

// extension to get parameters from url
$.extend({
    getUrlVars: function()
    {    
        var vars = [], hash;    
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
        for(var i = 0; i < hashes.length; i++)    
        {      
            hash = hashes[i].split('=');      
            vars.push(hash[0]);      
            vars[hash[0]] = hash[1];    
        }    
        return vars;  
    },  
    getUrlVar: function(name)
    {    
        return $.getUrlVars()[name];  
    }
});

// extension to encode / decode parameters
$.extend({
    URLEncode:function(c)
    {
        var o='';
        var x=0;
        c=c.toString();
        var r=/(^[a-zA-Z0-9_.]*)/;
        while(x<c.length)
        {
            var m=r.exec(c.substr(x));
            if(m!=null && m.length>1 && m[1]!='')
            {
                o+=m[1];
                x+=m[1].length;
            }
            else
            {
                if(c[x]==' ')
                    o+='+';
                else
                {
                    var d=c.charCodeAt(x);
                    var h=d.toString(16);
                    o+='%'+(h.length<2?'0':'')+h.toUpperCase();
                }
                x++;
            }
        }
        return o;
    },
    URLDecode:function(s)
    {
        var o=s;
        var binVal,t;
        var r=/(%[^%]{2})/;
        while((m=r.exec(o))!=null && m.length>1 && m[1]!='')
        {
            b=parseInt(m[1].substr(1),16);
            t=String.fromCharCode(b);
            o=o.replace(m[1],t);
        }
        return o;
    }
});
