// 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);
}

/* translation support*/
function getTranslation (msg)
{
	var translation = JSTranslations[msg];
	if(typeof(translation) == "undefined")
		translation = msg;
	if(arguments.length > 1)
	{
		for(var i=0;i<arguments.length-1;i++)
		{
			translation = translation.replace(new RegExp("\\{"+i+"\\}"), arguments[i+1]);
		}
	}
	return translation;
}

/* Disable ViewSource */ 
function DisableViewSourceStart()
{
	var timeoutCopyrightAlert = 500;
	var canDisplayAlert = true;
	log.info("Copyright protection enabled (timeout "+timeoutCopyrightAlert+" ms)");
	function displayCopyrightAlert(e)
	{
		var target = e.target;
		
		if(target != null && target.tagName != "INPUT" && target.tagName != "TEXTAREA")
		{	
			if(canDisplayAlert)
			{
				canDisplayAlert = false;
				alert("Copyright (c) " + new Date().getFullYear() + " Bureau van Dijk");
				//We add a timeout to avoid having multiple alerts
				window.setTimeout(function(){
					canDisplayAlert = true;
				}, timeoutCopyrightAlert);
			}
			return false;
		}
		return true;
	}

	function selectEnd(evt)
	{
		// 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)
		{
			// cannot find the definition of the method...
			if(typeof(ShowViewSourceAlert) != "undefined")
				ShowViewSourceAlert(); 
			return false;
		}		    

		var target = evt.target;
		if (target == null)
			return true;
			
		if(target.style.overflow == "auto" || target.style.overflowY == "auto" || target.style.overflowX == "auto")
			return true;
	     
		return displayCopyrightAlert(evt);
	}

	// should be broken for js bounded events. Check.
	function hasMouseHandlers(target)
	{
		var targetStr = "";
	      
		do
		{
			// might want to check for additional events...
			if (target.onclick != null || target.onmousedown != null)
				return true;
			targetStr = target.tagName.toLowerCase();    
			if (targetStr == "a" || targetStr == "select" || targetStr == "input" || targetStr == "label" /*|| targetStr == "html"*/)
				 return true;
	          
			if($(target).data("events") != null)
				return true;

			target = target.parentNode;
		  } 
		  while (target != null && targetStr != "body" && targetStr != "html");
	      
		return false;
	}

	function hideBeforePrint()
	{
		for(var 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 showAfterPrint()
	{
		for(var wi=0; wi<document.all.length; wi++)
		{
			if(document.all[wi].viewSourceMarker=="gwp")
				document.all[wi].style.visibility='';
		}
	}

	var selectEvents = 
	{
		endMove:function(e)
		{
			selectEnd(e);
			$(document).
				unbind("mousemove", selectEvents.move).
				unbind("mouseup", selectEvents.endMove).
				unbind("selectStart", selectEvents.selectStart);
			$(document).blur();

		},
		selectStart:function (e)
		{
			if(hasMouseHandlers(e.target))
				return true;
			$(document).
				bind("mousemove", selectEvents.move);
			return false;
		},
		move:function(e)
		{	
			$(document).
				unbind("mousemove", selectEvents.move).
				bind("mouseup", selectEvents.endMove);
		}
	};		

	//Save to disk
	if(window.location.protocol.indexOf("file")!=-1)
		location="about&#058;blank";
		
	//Select
	$(document)
		.mousedown(selectEvents.selectStart)
	// dblClick FF and CHROME
		.dblclick(displayCopyrightAlert)
	// dblClick IE
		.bind("selectstart", displayCopyrightAlert)
	//Right click
		.bind("contextmenu", displayCopyrightAlert);
	
	//direct print
	window.onbeforeprint=hideBeforePrint;
	window.onafterprint=showAfterPrint;
}

/* Client Resolution */
var clientResolution=(function(window, $){
	var prevClientRes = null, originalClientRes = null,  clientResTimeoutId = null, win = $(window), minres=null,form;
	// We directly evaluate the isPopUpWindow function.
	var isPopUpWindow = (function ()
	{
		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 getResolutionString() 
	{
		return win.width() + "x" + win.height();
	}
	
	function getMinimisedResolutionString() 
	{
		var width = win.width(), height=win.height();
		if(!!minres)
		{
			width = Math.max(minres.width, width);
			height = Math.max(minres.height, height);
		}
		return width + "x" + height;
	}
	
	function onResize(sync, timeout, strat, stratArgs)
	{
		if(!strat)
			return;
		if (isPopUpWindow && strat !== volatileResolution)
			return;
	
		// we dont send the client resolution to the server when the scrollbar is hidden (ModalLayerDialog)			
		if (document.body.style.overflow == "hidden")
			return;
	
		if (clientResTimeoutId != null)
			window.clearTimeout (clientResTimeoutId);
	
		if(sync)
		{
			waitBeforeUpdating();
		}
		else
			clientResTimeoutId = window.setTimeout(waitBeforeUpdating, timeout);
		
		function waitBeforeUpdating()
		{
			
			var clientResolutionString = getMinimisedResolutionString();
			if(clientResolutionString === "0x0") // In a iFrame for salesforce
			{
			  return;
			}   
			if(clientResolutionString === prevClientRes){ // don't update if resolution has not changed
				return;
			}
			if(!stratArgs)
				stratArgs = [];
			strat.apply(this, stratArgs);
			
			prevClientRes = clientResolutionString;
			  
			clientResTimeoutId = null;
		}
	}
	
	// STRATEGIES ///////////////////////
	function sendToUrl(url)
	{
		if (!url) return;
		
		$.get(url, {'clientRes':getMinimisedResolutionString()});
	}
	
	function storeInInput(inputName) 
	{
		if (!inputName) return false;

		//Create a hidden input that contains Height and width.
		var input = $("input[name="+inputName+"]");
		if(input.length === 0){
			input = $("<input>", {"name":inputName, "type":"hidden"}).appendTo(form);
		}
		
		input.val(getMinimisedResolutionString());
		return true;
	}
	
	function storeAndPostBack(inputName, url)
	{
		// Strategy is broken without a minimum resolution and not point doing a post back if there's no resolution
		if(!minres  || !storeInInput(inputName))
			return;
		if(url && !isSignificantChange())
		{
			log.debug("Resolution change is less than 10 percent. Using the sendtoUrl strategy.");
			sendToUrl(url);
			return;
		}
		
		postPack();
	}
	
	function volatileResolution()
	{
		var hasChanged = false;
		form.attr("action",function(i,oldAction)
		{
			var newAction = oldAction.replace(/VolatileResolution=\d+x\d+/i, "VolatileResolution="+getMinimisedResolutionString());
			hasChanged = newAction != oldAction;		
			return newAction;
		});
		
		if(hasChanged && isSignificantChange())
			postPack();
	}
	
	// Helpers ///////////////////////
	function postPack()
	{
		// The list page define the RefreshPageDelegate and that does a partial update of the list content.
		if (typeof(__doPostBack)=='function')
			__doPostBack("", "");
		else
			form.submit();
	}
	
	function isSignificantChange()
	{
		if(originalClientRes)
		{
			var previous = originalClientRes.split('x');
			var w = isLessThan10Percent(previous[0], win.width());
			var h = isLessThan10Percent(previous[1], win.height());
			if(w && h)
			{
				return false;
			}
		}
		return true;
	}
	
	function isLessThan10Percent(old, current)
	{
		log.debug("old:"+old+" current:"+current);
		var ratio = (current-old) / old;
		return -0.1 < ratio && ratio < 0.1;
	}

	//Binds resolution change strategies to the enum defined in ClientResolutionManager.ResolutionChangeStrategy
	var strategies=
	{
		"Url":sendToUrl,
		"Hidden":storeInInput,
		"Refresh":storeAndPostBack,
		"Volatile":volatileResolution
	};
	
	function checkPrevRes(previousRes)
	{
		if(!previousRes || !minres)
			return previousRes;
		var wh = previousRes.split("x");
		wh[0] = Math.max(minres.width, wh[0]);
		wh[1] = Math.max(minres.height, wh[1]);
		return wh.join('x');
	}
	
	//Global publishing strategy
	//function getClientResolutionString is used in other scripts. We publish it.
	window["getClientResolutionString"] = getResolutionString;
	
	return {
		init:function (config)
		{
			if(!config)
				return;
			this.isTouchPad = config.isTouchPad;
			// if the form is generated multiple times
			form=$("form:first");
			minres = config.minResolution;
			originalClientRes = prevClientRes = checkPrevRes(config.previousRes);
			var resolutionChangeStrategy = strategies[config.strategy];
			var handler = function(){
				onResize.call(this, config.sync||false, config.timeout||500,resolutionChangeStrategy, config.strategyArgs);
			};
			// We wait for the browser before checking resolution changes.
			$(function(){
				win.unbind(".clientResolution").bind("resize.clientResolution", handler).resize();
			});
		},
		width:function(){
			return win.width();
		},
		height:function(){
			return win.height();
		}};
})(this, jQuery);

// 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 (GET only) from url
$.extend({
	getUrlVars: function()
	{
		var vars = [],
			url = document.forms[0].action,
			hashes = url.slice(url.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++)
		{
			var hash = hashes[i].split('=');
			vars[hash[0].toLowerCase()] = hash[1];
		}
		return vars;
	},
	getUrlVar: function(name)
	{
		return $.getUrlVars()[name.toLowerCase()];
	}
});

function jq(myid) { 
	return '#' + myid.replace(/(:|\.)/g,'\\$1');
}


// 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;
    }
});

// JQuery to allow Watermark Effect in TextBox
$(function() {

    $(".inputWithGrayedTextInfo").focus(function() {
        var $tb = $(this);
        if ($tb.val() == this.title) {
            $tb.val("");
            $tb.removeClass("inputWithGrayedTextInfo");
        }
    }).blur(function() {
        var $tb = $(this);
        if ($.trim($tb.val()) == "") {
            $tb.val(this.title);
            $tb.addClass("inputWithGrayedTextInfo");
        }
    }).each(function() {
        var $tb = $(this);
        if($tb.val().length == 0)
        {
            $tb.blur();
        }
        else if ($tb.val() != this.title) {
            $tb.removeClass("inputWithGrayedTextInfo");
        }
    });
    
    var vs= $("input[name='__VIEWSTATE']");
    if (vs.length > 0)
			log.info("ViewState is "+vs.val().length+" bytes");
});        

