﻿function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) 
  {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1) 
      return element;

    elements.push(element);
  }

}
var ns4 = document.layers;
var op5 = (navigator.userAgent.indexOf("Opera 5")!=-1) 
	||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6 = (navigator.userAgent.indexOf("Opera 6")!=-1) 
	||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt=navigator.userAgent.toLowerCase();
var mac = (agt.indexOf("mac")!=-1);
var ie = (agt.indexOf("msie") != -1); 
var ie6 = ie && (agt.indexOf("6.") > -1 || agt.indexOf("5.") > -1); 
var mac_ie = mac && ie;
var mouseX, mouseY;
var indexes = 100;
var UserInfo;
var LastBalloonPosX,LastBalloonPosY;

StringBuilder = function()
{
    this.Value = "";
}
StringBuilder.prototype.Append = function(s)
{
    this.Value += s;
}
StringBuilder.prototype.ToString = function()
{
    return this.Value;
}

function getMousePos(e)
{
	if (!e)
		var e = window.event||window.Event;
	
	if(typeof e.pageX != 'undefined'){
		mouseX = e.pageX;
		mouseY = e.pageY;
	} else {
	    if (document.body)
	    {
		    mouseX = e.clientX + GetScrollLeft();
		    mouseY = e.clientY + GetScrollTop();
		}
	}
}

function GetScrollTop()
{
    var pos = 0;
    if (window.pageYOffset)
    {
	      pos = window.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    {
	    pos = document.documentElement.scrollTop;
    }
    else if (document.body)
    {
	    pos = document.body.scrollTop;
    }
    return pos;
}

function GetScrollLeft()
{
    var pos = 0;
    if (window.pageXOffset)
    {
	      pos = window.pageXOffset;
    }
    else if (document.documentElement && document.documentElement.scrollLeft)
    {
	    pos = document.documentElement.scrollLeft;
    }
    else if (document.body)
    {
	    pos = document.body.scrollLeft;
    }
    return pos;
}

// You need to tell Mozilla to start listening:
// document.captureEvents deprecated aparently?
//if(window.Event && document.captureEvents)
//	document.captureEvents(Event.MOUSEMOVE);

// Then assign the mouse handler
// Assign the mouse handler
if (document.attachEvent)
{
    document.attachEvent("onmousemove", function() { getMousePos(event); } );
}
else
{
    window.addEventListener("mousemove", function(e) { getMousePos(e); }, false );
}
function GetModuleHeight()
{
    var winH = window.innerHeight ? window.innerHeight: document.documentElement.offsetHeight;
    var h = winH - (PosY($('ModuleHolderTable'))+GetHeight($('Footer')));
    return h>1?h:1;
}
/*

function ResizeModuleHolderTable()
{
    if (!$('ModuleHolderTable'))
        return;
        
    $('ModuleHolderTable').style.height = GetModuleHeight()+'px';
}

if (window.attachEvent)
{
    window.attachEvent("onresize", ResizeModuleHolderTable);
}
else
{
    window.addEventListener("resize", function() { ResizeModuleHolderTable() }, false );
}
if (window.attachEvent)
{
    document.body.attachEvent("onload", ResizeModuleHolderTable);
}
else
{
    document.addEventListener("load", function() { ResizeModuleHolderTable() }, false );
}
*/
function PosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
	{
		curleft += obj.x;
    }
	return curleft;
}

function PosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
	{
		curtop += obj.y;
    }
	return curtop;
}
function OpenMap(EntityID, address)
{
    $('MapWindow').style.width = '520px';
    $('MapWindow').style.height = '350px';
    $('MapWindow').src = 'http://maps.veetro.com/?address='+address;
    $('MapHolder').style.left = (PosX($('APos'+EntityID)))+'px';
    $('MapHolder').style.top = (PosY($('APos'+EntityID))-200)+'px';
    $('MapHolder').style.display = 'block';
    
}
function CloseMap()
{
    $('MapHolder').style.display = 'none';
}
function DescriptiveTextBoxOnLeave(sender, description)
{
    if (sender.value==null||sender.value.length==0)
    {
        sender.value = description;
        sender.className = sender.className+' EmptyTextBox';
    }
    else
    {
       RemoveEmptyTextBoxClass(sender);
    }
}
function DescriptiveTextBoxOnEnter(sender, description)
{
    if (sender.value==description)
    {
        sender.value = '';  
    }
    RemoveEmptyTextBoxClass(sender);
}
function RemoveEmptyTextBoxClass(sender)
{
    if (sender.className)
        sender.className = sender.className.replace(/EmptyTextBox/g,'');
}
function GetDescriptiveTextBoxValue(ClientID, description)
{
    if ($(ClientID).value==description)
        return '';
    else
        return $(ClientID).value;
}
function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}
function GetHeight(elem)
{
    if (ns4) 
    {
		xPos = elem.clip.height;
	} 
	else if (op5) 
	{ 
		xPos = elem.style.pixelHeight;
	} 
	else 
	{
    	xPos = elem.offsetHeight;
	} 
	return xPos;
}

function GetWidth(elem)
{
    if (ns4) 
    {
		xPos = elem.clip.width;
	} 
	else if (op5) 
	{ 
		xPos = elem.style.pixelWidth;
	} 
	else 
	{
    	xPos = elem.offsetWidth;
	} 
	return xPos;
}

var maxSteps = 10;
function __Toggle(id, div)
{
    
	
		

    var newView = $(id).style.display=="none"?"block":"none";
    
    if (div)
    {
        if (newView=="block")
            div.className = div.className.replace('ExpandPanelUp', 'ExpandPanelDown');
        else
            div.className = div.className.replace('ExpandPanelDown', 'ExpandPanelUp')

	}
    if ( $(id+"_state"))
        $(id+"_state").value = newView=="block"?"1":"0";
        
    var originalPosition = $(id).style.position;
    $(id).style.display = "block";
    var originalSize = GetHeight($(id));
    $(id).style.display = "none";
    //$(id).style.position = "absolute";
    $(id).style.overflow = "hidden";
    
    if (newView=="block")
    {
         $(id).style.height = "0px";
         $(id).style.display = "block";
         OnAnimTimer(id, 0, newView,  originalSize, originalPosition);
         
    }
    else
    {
       
        $(id).style.display = "block";
        OnAnimTimer(id, 0, newView,  originalSize, originalPosition);
    }
}

function OnAnimTimer(id, step, view, originalSize, originalPosition)
{
    var end = view == "block" ? originalSize : 0;
    var start = view == "block" ? 0 : originalSize;
    var height = EaseInOut(start, end, maxSteps, step, 1);
    
    if (step==maxSteps)
    {
        if (view=="block")
        {
            $(id).style.height = null;
        }
        else
        {
            $(id).style.display = 'none';
        }
        $(id).style.position = originalPosition;
    }
    else
    {
        $(id).style.height = height+'px';
        setTimeout("OnAnimTimer('"+id+"', "+(step+1).toString()+", '"+view+"', "+originalSize+", '"+originalPosition+"');", 10);
    }
}
function EaseInOut(minValue,maxValue,totalSteps,actualStep,powr) 
{ 
//Generic Animation Step Value Generator By www.hesido.com
    totalSteps = Math.max(totalSteps,1)
    var delta = maxValue - minValue; 
    var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta); 
    return Math.ceil(stepp) 
} 

function DisableSelection(element) {
    element.onselectstart = function() {
        return false;
        };
    element.unselectable = "on";
    element.style.MozUserSelect = "none";
    element.style.cursor = "default";
}
function EnableSelection(element) {
    element.onselectstart = null;
    element.unselectable = "";
    element.style.MozUserSelect = "";
    element.style.cursor = "default";
}
function FormatDateUTC(d, forUrl)
{
    var minuteSep = forUrl?'.':':';
    
    if (d.getHours()>0 || d.getMinutes()>0|| d.getSeconds()>0 || forUrl) // only convert when there's time of some sort
        return d.getUTCFullYear().toString()+'-'+(d.getUTCMonth()+1).toString()+'-'+d.getUTCDate().toString()+' '+d.getUTCHours().toString()+minuteSep+d.getUTCMinutes().toString()+minuteSep+d.getUTCSeconds().toString();
    else
        return d.getUTCFullYear().toString()+'-'+(d.getUTCMonth()+1).toString()+'-'+d.getUTCDate().toString();
}


function PadZero(num) 
{
	return (num	< 10)? '0' + num : num;
}
function RdNthEtc( number )
{
    var num = number.toString();
    var txt = num;

    var lastChar = num.charAt(num.length-1);

    if (lastChar == "1" && ( number < 10 || number > 19 ))
        txt += ( "st " );
    else if (lastChar == "2" && ( number < 10 || number > 19 ))
        txt += ( "nd " );
    else if (lastChar == "3" && ( number < 10 || number > 19 ))
        txt += ( "rd " );
    else if (( lastChar == "4" ||
        lastChar == "5" ||
        lastChar == "6" ||
        lastChar == "7" ||
        lastChar == "8" ||
        lastChar == "9" ||
        lastChar == "0" ||
        ( number > 10 && number < 19 )
        ) && number > 3)

        txt += ( "th " );
    return txt;
}
function FormatDate(date, format)
{
    var sTmp = format;
    sTmp = sTmp.replace	(/Dth/g,"<~>"); // th rd nd etc
	sTmp = sTmp.replace	(/dddd/g,"<!!!!>");
	sTmp = sTmp.replace	(/ddd/g,"<!!!>");
	sTmp = sTmp.replace	(/dd/g, "<!!>");
	sTmp = sTmp.replace	(/d/g, "<!>");
	sTmp = sTmp.replace	(/yyyy/gi, "<****>");
	sTmp = sTmp.replace	(/yy/gi, "<**>");
	sTmp = sTmp.replace	(/MMMM/g, "<@@@@>");
	sTmp = sTmp.replace	(/MMM/g, "<@@@>");
	sTmp = sTmp.replace	(/MM/g, "<@@>");
	sTmp = sTmp.replace	(/M/g, "<@>");
	sTmp = sTmp.replace	(/mm/g, "<##>");
	sTmp = sTmp.replace	(/m/g, "<#>");
    sTmp = sTmp.replace	(/HH/g, "<$$>");
	sTmp = sTmp.replace	(/H/g, "<$>");
	sTmp = sTmp.replace	(/hh/g, "<^^>");
	sTmp = sTmp.replace	(/h/g, "<^>");
	sTmp = sTmp.replace	(/ss/g, "<((>");
	sTmp = sTmp.replace	(/s/g, "<(>");
	sTmp = sTmp.replace	(/tt/gi, "<&>");
	
	sTmp = sTmp.replace	("<~>",  RdNthEtc(date.getDate()).trim());
	sTmp = sTmp.replace	("<!!!!>",  fullDayNames[date.getDay()]);
	sTmp = sTmp.replace	("<!!!>",  shortDayNames[date.getDay()]);
	sTmp = sTmp.replace	("<!!>", PadZero(date.getDate()));
	sTmp = sTmp.replace	("<!>", date.getDate());
	sTmp = sTmp.replace	("<@@@@>", fullMonthNames[date.getMonth()]);
	sTmp = sTmp.replace	("<@@@>", shortMonthNames[date.getMonth()]);
	sTmp = sTmp.replace	("<@@>", PadZero(date.getMonth()+1));
	sTmp = sTmp.replace	("<@>", date.getMonth()+1);
	sTmp = sTmp.replace	("<##>", PadZero(date.getMinutes()));
	sTmp = sTmp.replace	("<#>", date.getMinutes());
	sTmp = sTmp.replace	("<((>", PadZero(date.getSeconds()));
	sTmp = sTmp.replace	("<(>", date.getSeconds());
	
	sTmp = sTmp.replace	("<$$>", PadZero(date.getHours()+1));
	sTmp = sTmp.replace	("<$>", date.getHours());
	sTmp = sTmp.replace	("<^^>", PadZero(date.getHours()>12?date.getHours()-12:date.getHours()));
	sTmp = sTmp.replace	("<^>", date.getHours()>12?date.getHours()-12:date.getHours());
	sTmp = sTmp.replace	("<&>", date.getHours()<12?amDesignator:pmDesignator);
	
	sTmp = sTmp.replace	("<****>", date.getFullYear());
	sTmp = sTmp.replace	("<**>", date.getFullYear().toString().substring(2));

	return sTmp;
}

function Global_CB_(/* "Veetro.v2_0.ClassName.MethodName", param string[] args*/)
{
    var s = "";
    for (var i = 1; i < arguments.length; i++) 
    {
        if (s.length>0)
            s += "\n";
        if (arguments[i])
            s += arguments[i].toString().replace(/\n/g, "\\n");
    }
    return Global_CBInternal(arguments[0], s);
}

function GlobalCB(/* "Veetro.v2_0.ClassName.MethodName", param string[] args*/)
{
    var s = "";
    for (var i = 1; i < arguments.length; i++) 
    {
        if (s.length>0)
            s += "\n";
        if (arguments[i])
            s += arguments[i].toString().replace(/\n/g, "\\n");
    }
    PageMethods.set_path('/v2.0/Work.aspx');
    PageMethods.GlobalCBInternal(arguments[0], s, OnCallBackSuccess, OnCallBackFailure);
}
function CollectFormData()
{
    var s = "";
    var keys = new Array();
    var values = new Array();
    
    for(var i=0;i<document.forms[0].elements.length;i++)
    {
        var el = document.forms[0].elements[i];
        if ((el.tagName=='INPUT'
            || el.tagName=='SELECT'  || el.tagName=='TEXTAREA')
            && el.name
            && el.name!='__VIEWSTATE')
        {
            if ((el.type=='radio'||el.type=='checkbox') && !el.checked)
                continue;
            
            var idx =-1;
            for(var x=0;x<keys.length;x++)
            {
                if (keys[x].toLowerCase()==document.forms[0].elements[i].name.toLowerCase())
                {
                    idx = x;
                    break;
                }
            }
            
            if (idx==-1)
            {
                keys.push(document.forms[0].elements[i].name.toLowerCase());
                values.push(document.forms[0].elements[i].value);
                idx = keys.length-1;
            }
            else
                values[idx] += ","+document.forms[0].elements[i].value;
            
        }
    }
    for(var i=0;i<keys.length;i++)
    {
        if (s)
           s += "\n";
        s += keys[i]+'='+values[i].replace(/\n/g, "#NL#");
    }
    //alert(s);
    return s;
}
function OnCallBackSuccess(result, userContext, methodName)
{
    if (result && result.length>1)
        eval(result);
}

function OnCallBackFailure(error, userContext, methodName)
{
    alert("A javascript request has failed run successfully. We apologise for this inconvenience.\n\nIf you continue to receive this message, please contact support for assistance.");
    
}


function MarkModified()
{
    if ($('HasFormChanged'))
        $('HasFormChanged').value='1';
}
function CancelEdit()
{
    if ($('HasFormChanged'))
        $('HasFormChanged').value='0';
}

function FixIe6Hover() 
{
    if (!ie6)
        return;
        
    var uls = document.getElementsByTagName("UL");
    for(var x=0;x<uls.length;x++)
    {
        if (uls[x].className!="MiniDropDown")
            continue;
            
	    var sfEls = uls[x].getElementsByTagName("LI");
    	
	    for (var i=0; i<sfEls.length; i++) 
	    {
		    sfEls[i].onmouseover=function() 
		    {
			    this.className+=" sfhover";
		    }
		    sfEls[i].onmouseout=function() 
		    {
			    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		    }
    		
	    }
	}
}

if (ie6) 
    window.attachEvent("onload", FixIe6Hover);

function PushTimeZone()
{
    var d = new Date();
    GlobalCB('Calendar.StoreTimezoneBias', d.getTimezoneOffset());
}

function SetEntryProgress(event, sender, type, id)
{
    var width = GetWidth(sender);
    if (width==0)
        return;
    
    var containerLeft = PosX(sender);
    
    var x = Math.round((mouseX-containerLeft)/width * 100);
    if (x>95)
        x = 100;
    if (x < 5)
        x = 0;
    //sender.childNodes[0].innerHTML = "<div class=\"Value\">"+x+"%</div>";
    //sender.childNodes[0].style.width = x+"%";
    sender.innerHTML = "<img src=\"/v2.0/images/spinner.gif\"/>";
    GlobalCB('CalendarWidget.SetEntryProgress', id, x.toString()+" ");
}

DayOfWeek =
{
      "Sunday":0,
      "Monday":1,
      "Tuesday":2,
      "Wednesday":3,
      "Thursday":4,
      "Friday":5,
      "Saturday":6
}

Date.prototype.addMonths = function (n) { 
 var day = this.getDate(); 
 this.setMonth(this.getMonth() + n); 
 if (this.getDate() < day) { 
  this.setDate(1); 
  this.setDate(this.getDate() - 1); 

 } 
 return this; 
} 

Date.prototype.addDays = function (n) { 
 AddDays(this, n);
 return this; 
} 

Date.prototype.addMinutes = function (n) { 
 this.setTime(this.getTime()+n*1000*60);
 return this; 
} 

Date.prototype.getWeekOfYear = function() {
    var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
    var DoW = d.getDay();
    d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
    var ms = d.valueOf(); // GMT
    d.setMonth(0);
    d.setDate(4); // Thu in Week 1
    return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
}

function parseDate(value, format)
{
    var rx = new RegExp("(h?h|m?m|tt|d?d|M{1,3}|yyyy)", "g");
    var searchPattern = "";
    var match = rx.exec(format);
    var indexes = new Object();
    var d = new Date();
    var hasTime = false;
    
    if (match!=null 
        && match.length>0)
	{
		var x = 0;
		while(match != null)
		{
			x++;
			for (var i=1; i<match.length; i++)
			{

				if (match[i]=='h' || match[i]=='hh' || match[i]=='HH')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
				    searchPattern += '(\\d?\\d)?';
					indexes.Hour = x;
					hasTime = true;
				}
				if (match[i]=='m' || match[i]=='mm')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
					searchPattern += '(\\d?\\d)?';
					indexes.Minute = x;
					hasTime = true;
				}
				if (match[i]=='tt')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]*';
					searchPattern += '('+UserInfo.AMDesignator+'|'+UserInfo.PMDesignator+')?';
					indexes.AMPM = x;
					hasTime = true;
				}
				if (match[i]=='d' || match[i]=='dd')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
					searchPattern += '(\\d?\\d)';
					indexes.Day = x;
				}
				if (match[i]=='MM'|| match[i]=='M')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
					searchPattern += '(\\d?\\d)';
					indexes.Month = x;
				}
				if (match[i]=='MMM')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
					searchPattern += '(\\w{3})';
					indexes.MonthName = x;
				}
				if (match[i]=='yyyy')
				{
				    if (searchPattern.length>0)  
				        searchPattern += '[^\\w]+';
					searchPattern += '(\\d{4})';
					indexes.Year = x;
				}
			}
			match = rx.exec(format);
		}
		
	
        searchPattern = ".*?"+searchPattern+".*?";
        this.HasTime = indexes.Hour?true:false;
        
		var formattedRx = new RegExp(searchPattern, "i");
		var dataMatch = formattedRx.exec(value);
		
		if (dataMatch!=null)
		{
		    if (hasTime && dataMatch[indexes.Hour] && dataMatch[indexes.Minute])
		    {
		        var pm = dataMatch[indexes.AMPM] && dataMatch[indexes.AMPM].toLowerCase()=='pm';
		        var hour = parseInt(dataMatch[indexes.Hour], 10);
		        if (pm)
		        {
		            if (hour<12)
		                hour += 12;
		        }
			    d.setHours(hour);
			    d.setMinutes(parseInt(dataMatch[indexes.Minute], 10));;
			    d.setSeconds(0);
			}
			else
			{
			    d.setHours(0);
                d.setMinutes(0);
                d.setSeconds(0);
			}
			d.setDate(parseInt(dataMatch[indexes.Day], 10));
			
			if (indexes.Month)
				d.setMonth(parseInt(dataMatch[indexes.Month], 10)-1);
				
			else if (indexes.MonthName)
			{
				for	(var j=0;j<12;j++)
				{
					if (dataMatch[indexes.MonthName]==UserInfo.MonthNames[j])
					{
						d.setMonth(j);
						break;
					}
				}
			}
			
			d.setFullYear(dataMatch[indexes.Year]);
		}
		
		
	}
	else
	    alert("Unable to convert '"+value+"' into date. Please enter a value in the format of '"+format+"'");
	    
	return d;
}

function AddMonths(date, n)
{
    var d = new Date(date);
    var day = d.getDate(); 
    d.setMonth(d.getMonth() + n); 
    if (d.getDate() < day) 
    { 
    d.setDate(1); 
    d.setDate(d.getDate() - 1); 
    }
    return d;
}
function AddDays(date, n)
{
    var d = new Date(date);
    
    var offset1 = d.getTimezoneOffset();
    
    d.setTime(d.getTime()+n*1000*60*60*24);
    var offset2 = d.getTimezoneOffset();
    if (offset1!=offset2)
    {
        d.setTime(d.getTime()+((offset2-offset1)*60*1000));
       // window.status=('offset dif '+(offset2-offset1)+' mins');
    }
        
    return d;
}
function AddYears(date, n)
{
    var d = new Date(date);
    d.setTime(d.getTime()+n*365*1000*60*60*24);
    return d;
}
function LoadUserInfo(OnLoaded)
{
    if (UserInfo)
    {
        if (OnLoaded)
            eval(OnLoaded);
        return;
    }   
    GlobalCB('Calendar.LoadUserInfo', OnLoaded);
    
}

function HtmlEncode(s)
{
    if (!s)
    return "";
    
    return s.replace(/"/g, "&quot;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
}
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function BuildColorPicker(holderID, fieldID, initialValue)
{
    var s = "";
    
    s += "<div id=\""+fieldID+"_popup\"></div><table><tr><td id=\""+fieldID+"_preview\" class=\"GradOverlay\" onclick=\"OpenColourPicker('"+fieldID+"');\" style=\"width: 22px; height: 18px; border:1px solid #555555; cursor: pointer;\"></td><td><input style=\"width: 60px; border:1px solid #555555; cursor: pointer;height: 18px;\" onkeyup=\"UpdateColourPicker('"+fieldID+"');\" onclick=\"OpenColourPicker('"+fieldID+"');\" type=\"text\" value=\""+HtmlEncode(initialValue)+"\" name=\""+fieldID+"\" id=\""+fieldID+"\" /></td></tr></table>"
    
    $(holderID).innerHTML  = s;
    UpdateColourPicker(fieldID);
}
function UpdateColourPicker(fieldID)
{
    $(fieldID+'_preview').style.backgroundColor = $(fieldID).value.replace(/\s/g, "");
}
function SetColourPicker(fieldID, colour)
{
    $(fieldID).value = colour;
    UpdateColourPicker(fieldID);
}
function ColourPickerCancelClose()
{
    if (colourPickerTimeout)
        clearTimeout(colourPickerTimeout);
}
var colourPickerTimeout;
function CloseColourPicker(fieldID)
{
    ColourPickerCancelClose();
    colourPickerTimeout = setTimeout("CloseColourPickerDelayed('"+fieldID+"')", 500);
}
function CloseColourPickerDelayed(fieldID)
{
    $(fieldID+'_popup').innerHTML='';
}


function OpenColourPicker(fieldID)
{
    var s = "";
    
    //var colors = "#D3CBF9,#DFC3C2,#FDD1DE,#CEC2E5,#E3D7D1,#D3F8F8,#F6E4C5,#CDE8DB,#CEF7D8,#DDFAF2,#F4E5E0,#EEECF3,#F4FFD7,#DFCAFE,#D1D4FF,#E0FFD9,#E0C7CD,#E9E3EF,#FFF4E6,#D1ECF2,#CEE1CA,#EBE3F6,#DAD6EF,#F3E9C8,#C3C7D6,#CCD5D1,#D0EBD1,#E1D2DF,#E9D5C9,#C4CFD8,#F0F5FE,#E0F3E5,#FDD4F0,#DDE6DD,#FFE8C1,#C7EDCE,#E3C4F4,#CEC9FD,#F6D6FF,#FFD4DD,#CAEEF4,#EDF6E4,#D8C7DB,#C4F7D9,#EAC9FB,#FCEBEE,#DFE8C0,#E4F3C1,#FACFD6,#F3FECA,#DFC9D7,#C3F9C8,#C1E1D1,#C4FEF8,#F9C9C7,#CED7DB,#C7F7DB,#FDCEFE,#DBD3F1,#D3E4DD,#DFE3EA,#E8D3C4,#EECEC4,#E5CCD6,#E9DFC2,#F6F7D6,#C5E3C0,#E3E6D8,#E3E4E0,#E0EED4,#DBEAE6,#EDC4DA,#E5E6E8,#C8F2DB,#E0D8EE,#F4DDC9,#C1C6DF,#C6D3D3,#E8CBC9,#E4CBEC,#CBC5C3,#C3CCE5,#EBF1FE,#CDD4FF,#C4F1EA,#C1E2D8,#FCEADA,#CAD8CD,#FEECF6,#EFF7D8,#ECF8D3,#D4F4EE,#D5D9EC,#C0E5C5,#E4FCC1,#E9C4EE,#E8F5D4,#C4FDE2,#F0FBD5,#F9C2C2";
    //var colors = "#D3CBF9,#DFC3C2,#FDD1DE,#CEC2E5,#E3D7D1,#D3F8F8,#F6E4C5,#CDE8DB,#CEF7D8,#DDFAF2,#F4E5E0,#EEECF3,#F4FFD7,#DFCAFE,#D1D4FF,#E0FFD9,#E0C7CD,#E9E3EF,#FFF4E6,#D1ECF2,#CEE1CA,#EBE3F6,#DAD6EF,#F3E9C8,#C3C7D6,#CCD5D1,#D0EBD1,#E1D2DF,#E9D5C9,#C4CFD8,#F0F5FE,#E0F3E5,#FDD4F0,#DDE6DD,#FFE8C1,#C7EDCE,#E3C4F4,#CEC9FD,#F6D6FF,#FFD4DD,#CAEEF4,#EDF6E4,#D8C7DB,#C4F7D9,#EAC9FB,#FCEBEE,#DFE8C0,#E4F3C1,#FACFD6,#F3FECA,#DFC9D7,#C3F9C8,#C1E1D1,#C4FEF8,#F9C9C7,#CED7DB,#C7F7DB,#FDCEFE,#DBD3F1,#D3E4DD,#DFE3EA,#E8D3C4,#EECEC4,#E5CCD6,#E9DFC2,#F6F7D6,#C5E3C0,#E3E6D8,#E3E4E0,#E0EED4,#DBEAE6,#EDC4DA,#E5E6E8,#C8F2DB,#E0D8EE,#F4DDC9,#C1C6DF,#C6D3D3,#E8CBC9,#E4CBEC,#CBC5C3,#C3CCE5,#EBF1FE,#CDD4FF,#C4F1EA,#C1E2D8,#FCEADA,#E2CDFF,#FFB8B5,#FFDDFF,#D6B5FF,#FFEDDD,#E2FFFF,#FFFFBE,#D2FFF7,#D6FFF0,#BAD8F0,#CDBEB8,#FFBAF5,#BEFFB0";
    var colors = "#A5D18C,#698559,#D1CF8C,#858359,#D1D1D1,#737C85,#B4C2D1,#858272,#D1C7B4,#85737B,#D1B4C1,#D1606D,#FFC4C4,#B38989,#FFE2C4,#B39E89,#B3AD89,#CCCCCC,#D8FFC4,#97B389,#B3B389,#C4FFE9,#89B3A3,#C6FFC4,#8BB389,#FFC4F9,#B389AE,#FF5EB9,#B34282,#FFC4D3,#B38994,#FF6C5E,#B34B42,#C4E3FF,#899FB3,#B3A389,#D3CBF9,#DFC3C2,#FDD1DE,#CEC2E5,#E3D7D1,#D3F8F8,#F6E4C5,#CDE8DB,#CEF7D8,#DDFAF2,#F4E5E0,#EEECF3,#F4FFD7,#DFCAFE,#D1D4FF,#E0FFD9,#E0C7CD,#E9E3EF,#FFF4E6,#D1ECF2,#CEE1CA,#EBE3F6,#DAD6EF,#F3E9C8,#C3C7D6,#CCD5D1,#D0EBD1,#E1D2DF,#E9D5C9,#EDC4DA,#E5E6E8,#C8F2DB,#E0D8EE,#F4DDC9";
    
    var ar = colors.split(',');
    
    s += "<table id=\""+fieldID+"_table\" onmouseout=\"CloseColourPicker('"+fieldID+"');\" onmousemove=\"ColourPickerCancelClose()\" cellpadding=\"0\" cellspacing=\"0\" border=\"1\" bgcolor=\"#ffffff\" style=\"border: 1px solid #555555; border-collapse: collapse;\">";
    s += "<tr>";
    for(var i=0;i<ar.length;i++)
    {
        if ((i%10)==0 && i>0)
        {
            s += "</tr><tr>";
        }
        s += "<td onmousemove=\"ColourPickerCancelClose()\" style=\"width: 15px; height: 12px; cursor: pointer;\" onclick=\"SetColourPicker('"+fieldID+"', '"+ar[i]+"')\" bgcolor=\""+ar[i]+"\"></td>";
    }
    s += "</tr>";
    s += "</table>";
    
    var holder = $(fieldID+"_popup");
    holder.innerHTML = s;
    var table = $(fieldID+"_table");
    table.style.position = "absolute";
    //table.style.top = (mouseY+10).toString()+"px"; //PosY($(fieldID))+GetHeight($(fieldID))+"px";
    //table.style.left = mouseX.toString()+"px"; //PosX($(fieldID))+"px";
    table.style.marginTop = "25px";
    table.style.zIndex = 200;
    
   
}
function FormatDateUTCUrlString(date1, date2, utc)
{
    var s = FormatDateUTC(date1, true);
    if (date2)
        s += ' to '+FormatDateUTC(date2, true);
    return s;
}

//
// PopupContactBubble
//
var PopupContactTimeout;
var PopupContactID=0;

function PopupContactBubble(event, entityid)
{
    if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
 
    if (PopupContactID==entityid)
        return;
           
    var x = mouseX;
    var y = mouseY;
    
    PopupContactTimeout = setTimeout("PopupContactBubbleThreaded("+entityid+")", 500);
}


function PopupContactBubbleThreaded(entityid)
{
    
        
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"PopupPreviewBubbleCancelDelayed();\" class=\"Close\"></a>";
    s += "<h2>Contact Details</h2>";
    
    s += "<span id=\"PreviewBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Fetching contact details ... <br/><br/></p></span>";
    s += "</div><div class=\"Triangle\"></div></div>";
    $("PreviewBalloonHolder").innerHTML = s;
    
    var x = mouseX;
    var y = mouseY;
    var balloon = $("PreviewBalloon");
    balloon.style.display = "block";
    balloon.style.left = (x-110)+"px";
    balloon.style.top = (y-(GetHeight(balloon)+30))+"px";
    PopupContactID = entityid;
    
    PopupContactTimeout = setTimeout("PopupContactDetailsThreaded("+entityid+")", 10);
}

function PopupContactDetailsThreaded(entityid)
{
    var detailsElement = $('PreviewBalloonDetails');
    if (!detailsElement)
        return;
        
    GlobalCB('Contacts.RenderContactBubble', entityid.toString());
   
}
function OnRenderContactBubble(res, entityid)
{
    var detailsElement = $('PreviewBalloonDetails');
    if (!detailsElement)
        return;
        
    detailsElement.innerHTML = res;
    
    var balloon = $("PreviewBalloon");
    
    var x = mouseX;
    var y = mouseY;
    x = (x-110);
    y = (y-(GetHeight(balloon)+30));
    
    var winW = window.innerWidth ? window.innerWidth: document.documentElement.offsetWidth;
    var width = GetWidth(balloon);
    if (y<0)
        y = 5;
    if (x+width>winW)
        x = winW-(width+20);
    balloon.style.left = x+"px";
    balloon.style.top = y+"px";
    PopupContactID = entityid;
    
    if (balloon.attachEvent)
    {
        window.attachEvent("onmousemove", PopupPreviewBubbleCancelTimeout);
        window.attachEvent("onmouseout", PopupPreviewBubbleCancel);
    }
    else
    {
        balloon.addEventListener("mousemove", function() { PopupPreviewBubbleCancelTimeout() }, false );
        balloon.addEventListener("mouseout", function() { PopupPreviewBubbleCancel() }, false );
    }

   if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
   PopupContactTimeout = 0;
}
function PopupPreviewBubbleCancel()
{
    if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
    PopupContactTimeout = 0;
      if (PopupContactID==0)
         PopupPreviewBubbleCancelDelayed();
      else
      {
      //  window.status = 'closing..';
           
         PopupContactTimeout = setTimeout("PopupPreviewBubbleCancelDelayed()", 1000);
      }
}
function PopupPreviewBubbleCancelTimeout()
{
    if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
    PopupContactTimeout = 0;
}
function PopupPreviewBubbleCancelDelayed()
{
    if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
     $("PreviewBalloonHolder").innerHTML = "";
     PopupContactID = 0;
     PopupContactTimeout = 0;
}
function DialogBalloonHolderCancel()
{
    $("DialogBalloonHolder").innerHTML = "";
}

//
// PopupItemBubble
//


function PopupItemBubble(event, type, pk, occurrence)
{
    if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
 
    if (PopupContactID==pk)
        return;
           
    PopupContactTimeout = setTimeout("PopupItemBubbleThreaded('"+type+"', "+pk+", "+occurrence+", "+mouseX+", "+mouseY+")", 500);
}
function PopupItemBubbleThreaded(type, pk, occurrence, x, y)
{
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"PopupPreviewBubbleCancelDelayed();\" class=\"Close\"></a>";
    
    s += "<span id=\"PreviewBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Fetching preview ... <br/><br/></p></span>";
    s += "</div><div class=\"Triangle\"></div></div>";
    $("PreviewBalloonHolder").innerHTML = s;
    
    if (x<110)
        x = 115;
    
    var balloon = $("PreviewBalloon");
    balloon.style.display = "block";
    balloon.style.left = (x-110)+"px";
    balloon.style.top = (y-(GetHeight(balloon)+30))+"px";
    PopupContactID = pk;
    
    PopupContactTimeout = setTimeout("PopupItemDetailsThreaded('"+type+"',"+pk+", "+occurrence+", "+x+", "+y+")", 10);
}
function PopupItemDetailsThreaded(type, pk, occurrence, x, y)
{
    var detailsElement = $('PreviewBalloonDetails');
    if (!detailsElement)
        return;

    GlobalCB('CalendarWidget.RenderItemBubble', type, pk.toString(), occurrence.toString(), x, y);
   
}
function OnRenderItemBubble(res, x, y)
{
    var detailsElement = $('PreviewBalloonDetails');
    if (!detailsElement)
        return;
        
    detailsElement.innerHTML = res;
    
    var balloon = $("PreviewBalloon");

    x = (x-110);
    y = (y-(GetHeight(balloon)+30));
    
    var winW = window.innerWidth ? window.innerWidth: document.documentElement.offsetWidth;
    var width = GetWidth(balloon);
    if (y<0)
        y = 5;
    if (x+width>winW)
        x = winW-(width+20);
    balloon.style.left = x+"px";
    balloon.style.top = y+"px";

    if (balloon.attachEvent)
    {
        window.attachEvent("onmousemove", PopupPreviewBubbleCancelTimeout);
        window.attachEvent("onmouseout", PopupPreviewBubbleCancel);
    }
    else
    {
        balloon.addEventListener("mousemove", function() { PopupPreviewBubbleCancelTimeout() }, false );
        balloon.addEventListener("mouseout", function() { PopupPreviewBubbleCancel() }, false );
    }

   if (PopupContactTimeout)
        clearTimeout(PopupContactTimeout);
   PopupContactTimeout = 0;
}





function __Popup( _url, pWidth, pHeight, extra) 
{
    if (!extra)
        extra = "";
    var pLeft = (screen.width) / 2 - (pWidth/2);
    var pTop = (screen.height) / 2 - (pHeight/2);
    var d = new Date();
    var unique = d.getTime();
    pWin = open(_url, 'popUpWin'+unique, 'width='+pWidth+',height='+pHeight+',left='+pLeft+',top='+pTop+',screenX='+pLeft+',screenY='+pTop+',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes'+extra);
    pWin.opener = this;
} 
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*
 * Also defined in Util.BuildFileUploader(...)
 */
function BuildFileUploader(fileType, javascript_id, Callback, Comment, FolderID, EntryID)
{
    var s = "";
    
    if (!FolderID)
        FolderID = "0";
    if (!EntryID)
        EntryID = "0";
    
    var url = "/v2.0/FlashFileUploader.swf?file_type="+fileType+"&javascript_id="+javascript_id+"&rnd="+(new Date()).toString().replace(/\:/g,"")+"&VeetroSession="+readCookie("VeetroSession")+"&FolderID="+FolderID+"&EntryID="+EntryID;
    if (Callback)
        url += "&Callback="+Callback;
    if (Comment)
        url += "&Comment="+Comment;
        
    s += "<object id=\""+javascript_id+"FileUploadFrame\" width=\"260\" height=\"25\" align=\"CENTER\" codebase=\"http://fpdownload.adobe.com/get/flashplayer/current/swflash.cab#version=9,0,15,0\"";
    s += " classid=\"clsid:D27CDB6E-AE6D-11CF-96B8-444553540000\"><param name=\"movie\" value=\""+url+"\"/>";
    s += "<param name=\"quality\" value=\"high\"/><param name=\"scale\" value=\"noScale\"/>";
    s += "<param name=\"FlashVars\" value=\"\"/>";
    s += "<param name=\"SeamlessTabbing\" value=\"false\"/>";
    s += "<embed ";
    s += " src=\""+url+"\"";
    s += " name=\""+javascript_id+"FileUploadFrame\"";
    s += "  width=\"260\"";
    s += "  height=\"25\"";
    s += "  quality=\"high\"";
    s += "  scale=\"noScale\"";
    s += "  FlashVars=\"\"";
    s += "  SeamlessTabbing=\"false\"";
    s += "  swliveconnect=\"true\"";
    s += "  pluginspage=\"http://www.adobe.com/go/getflashplayer\"";
    s += "  type=\"application/x-shockwave-flash\">";
    s += "</embed>";
    s += "</object>";

    //<iframe id='"+javascript_id+"FileUploadFrame' name='"+id+"FileUploadFrame' src=\"/v2.0/Upload.aspx?id=" + javascript_id + "&type="+fileType+"\" style=\"width: 280px; height:50px;\" frameborder=\"0\"></iframe>
    
    return s;
}

function EditComment(NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    
    commentDiv.innerHTML = "<div class=\"Loading\"></div>";
    
    GlobalCB("EntryEditor.GetNotationEditor", NotationID);
    
    
}
function OnGetNotationEditor(res, NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    commentDiv.innerHTML = res;
    setTimeout("HtmlEdit_OnInitialise('CommentEditor"+NotationID+"');", 500);
}

function EditCommentApply(NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    
    var newHtml = $("CommentEditor"+NotationID).value;
    
    GlobalCB("EntryEditor.UpdateNotation", NotationID, newHtml);
}

function OnUpdateNotation(res, NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    commentDiv.innerHTML = res;
}

function EditCommentCancel(NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    GlobalCB("EntryEditor.GetNotation", NotationID);
}

function OnGetNotation(res, NotationID)
{
    var commentDiv = $("Notation"+NotationID+"_Body");
    if (!commentDiv)
        return;
    commentDiv.innerHTML = res;
}

function MarkItemsAsRead(itemsString, ElementID, ElementID2)
{
    GlobalCB("EntryEditor.MarkItemsRead", itemsString);

    var el = $(ElementID);
    if (el)
        el.style.display = "none";
    el = $(ElementID2);
    if (el)
        el.style.display = "none";
}

/*
* Catch Tab logic from
* http://www.webdeveloper.com/forum/showthread.php?s=&threadid=32317
*/

function setSelectionRange(input, selectionStart, selectionEnd) 
{
  if (input.setSelectionRange) 
  {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) 
  {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function replaceSelection (input, replaceString) 
{
	if (input.setSelectionRange) 
	{
		var selectionStart = input.selectionStart;
		var selectionEnd = input.selectionEnd;
		input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);
    
		if (selectionStart != selectionEnd)
		{ 
			setSelectionRange(input, selectionStart, selectionStart + 	replaceString.length);
		}
		else
		{
			setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
		}

	}
	else if (document.selection) 
	{
		var range = document.selection.createRange();

		if (range.parentElement() == input) 
		{
			var isCollapsed = range.text == '';
			range.text = replaceString;

			 if (!isCollapsed)  
			 {
				range.moveStart('character', -replaceString.length);
				range.select();
			}
		}
	}
}
// We are going to catch the TAB key so that we can use it, Hooray!
function CatchTab(item,e)
{
	if(navigator.userAgent.match("Gecko"))
	{
		c=e.which;
	}
	else
	{
		c=e.keyCode;
	}
	if(c==9)
	{
		replaceSelection(item,String.fromCharCode(9));
		setTimeout("document.getElementById('"+item.id+"').focus();",0);	
		return false;
	}
		    
}
function ToggleCalendarIDShowState(id)
{
     if (!$('Calendar'))
        window.location = "/calendar?cid="+id;
}

function BasicGrid_Sort(uid, method, state, postData, column, type)
{
    GlobalCB('BasicGrid.OnCallback',
        uid, method, state, postData?CollectFormData():' ', 'sort', column, type);//+'_table'
}

function BasicGrid_SetTab(uid, method, state, postData, tab)
{
    GlobalCB('BasicGrid.OnCallback',
        uid, method, state, postData?CollectFormData():' ', 'tab', tab);
}
var BasicGrid_searchTimeout;
function BasicGrid_PerformSearch(uid, method, state, postData)
{
    var keywords = $(uid+'_kw').value;
   
    GlobalCB('BasicGrid.OnCallback',
        uid, method, state, postData?CollectFormData():' ', 'search', keywords);
}
function BasicGrid_Refresh(uid, method, state, postData)
{
     GlobalCB('BasicGrid.OnCallback',
        uid, method, state, postData?CollectFormData():' ', 'refresh');
}
function BasicGrid_Command(uid, method, state, postData, cmd, arg)
{
     GlobalCB('BasicGrid.OnCallback',
        uid, method, state, postData?CollectFormData():' ', 'cmd', cmd, arg);
}
function BasicGrid_PerformSearchDelayed(uid, method, state, postData)
{
    if (BasicGrid_searchTimeout)
        clearTimeout(BasicGrid_searchTimeout);

    BasicGrid_searchTimeout = setTimeout('BasicGrid_PerformSearch("'+uid+'","'+method+'", "'+state+'", "'+postData+'")', 1500);
}
function RefreshBasicGrid(uid)
{
    if ($(uid+"_RefreshCmd"))
        eval($(uid+"_RefreshCmd").value);
}
function ToggleHelp(HelpEntry)
{
    var IsHidden = $("HelpContent").style.display=="none";
    GlobalCB("HelpWidget.StoreHelpState", HelpEntry, IsHidden?"1":"0");
    __Toggle("HelpContent");
}

function PopupTagDialog(event, tagsElement, cssClass, EntityID)
{
    var x = mouseX;
    var y = mouseY;
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"PopupPreviewBubbleCancelDelayed();\" class=\"Close\"></a>";
    
    s += "<span id=\"TagBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Fetching tags ... <br/><br/></p></span>";
    s += "</div><div class=\"Triangle\"></div></div>";
    $("PreviewBalloonHolder").innerHTML = s;
    
    PositionBalloon(mouseX, mouseY);
    
    GlobalCB("Contacts.RenderTagDialog", tagsElement, cssClass?cssClass:' ', EntityID);
}

function PositionBalloon(x,y)
{
    if (!x)
    {
        x = LastBalloonPosX;
        y = LastBalloonPosY;
    }
    
   
    var balloon = $("PreviewBalloon");
     var posY = (y-(GetHeight(balloon)+30));
    if (posY<5)
        posY = 5;
        
    if (x<115)
        x = 115;
    balloon.style.display = "block";    
    balloon.style.left = (x-110)+"px";
    balloon.style.top = posY+"px";
    LastBalloonPosX = x;
    LastBalloonPosY = y;
}
function PositionBalloonTop(x,y)
{
    if (!x)
    {
        x = LastBalloonPosX;
        y = LastBalloonPosY;
    }
    var balloon = $("PreviewBalloon");
    balloon.style.display = "block";    
    balloon.style.left = (x-110)+"px";
    balloon.style.top = (y+30)+"px";
    
    LastBalloonPosX = x;
    LastBalloonPosY = y;
}
function CollectSelectedCheckBoxes(inputName)
{
    var inputs = document.getElementsByTagName('input');
    var selection = '';
    for(var i=0;i<inputs.length;i++)
    {
        if (inputs[i].name==inputName
            && inputs[i].checked)
        {
            if (selection.length>0)
                selection += ',';
            selection += inputs[i].value;
        }
    }
    return selection;
}

function ToggleAllByName(sender, name)
{
    var inputs = document.getElementsByTagName('input');
    for(var i=0;i<inputs.length;i++)
    {
        if (inputs[i].name==name)
            inputs[i].checked = sender.checked;
    }
}

function OpenFeedbackDialog()
{
     var x = mouseX;
    var y = mouseY;
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"TriangleTop\"></div><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"DialogBalloonHolderCancel();\" class=\"Close\"></a>";
    
    s += "<span id=\"TagBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Please wait ... <br/><br/></p></span>";
    s += "</div></div>";
    $("DialogBalloonHolder").innerHTML = s;
    
    PositionBalloonTop(mouseX, mouseY);
    
    GlobalCB("Home.RenderFeedbackForm", x, y, window.location);
}

function SendBetaFeedback(x,y)
{
    var feedback = $('BetaFeedback').value;
    
    if (feedback.length===0)
    {
        $('BetaFeedbackError').style.display = 'block';
        return;
    }

    $("TagBalloonDetails").innerHTML = "<p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Sending your feedback ... <br/><br/></p>";
    PositionBalloonTop(x, y);
    GlobalCB("Home.SendBetaFeedback", x, y, window.location, feedback);
}

function RemoveReminder(ReminderID)
{
    GlobalCB("EntryEditor.OnRemoveReminder", ReminderID);
    if ($("Reminder"+ReminderID))
        $("Reminder"+ReminderID).style.display='none';
}

function OpenReminderDialog(EntryID)
{
     var x = mouseX;
    var y = mouseY;
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"DialogBalloonHolderCancel();\" class=\"Close\"></a>";
    
    s += "<span id=\"ReminderBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Please wait ... <br/><br/></p></span>";
    s += "</div><div class=\"Triangle\"></div></div>";
    $("DialogBalloonHolder").innerHTML = s;
    
    PositionBalloon(mouseX, mouseY);
    
    GlobalCB("EntryEditor.OnRenderReminderForm", EntryID, x, y);
}

function SetReminder(EntryID, x,y)
{
    var type = $('ReminderType_value').value;
    var offset = $('ReminderOffset_value').value;

    $("ReminderBalloonDetails").innerHTML = "<p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Saving reminder ... <br/><br/></p>";
    PositionBalloon(x, y);
    GlobalCB("EntryEditor.OnSetReminder", EntryID, type, offset);
}


function OpenPaymentDialog(InvoiceID)
{
     var x = mouseX;
    var y = mouseY;
    var s = "";
    s += "<div id=\"PreviewBalloon\" class=\"NewEntryBaloon\"><div class=\"Inner\">";
    s += "<a href=\"javascript:;\" onclick=\"DialogBalloonHolderCancel();\" class=\"Close\"></a>";
    
    s += "<span id=\"PaymentBalloonDetails\"><p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Please wait ... <br/><br/></p></span>";
    s += "</div><div class=\"Triangle\"></div></div>";
    $("DialogBalloonHolder").innerHTML = s;
    
    PositionBalloon(mouseX, mouseY);
    
    GlobalCB("Finances.OnRenderPaymentDialog", InvoiceID, x, y);
}

function SetPayment(InvoiceID, x, y)
{
    var date = $('PaymentDate').value+' ';
    var amount = $('PaymentAmount').value+' ';
    var receipt = $('PaymentReceipt').value+' ';
    var account = $('PaymentAccount_value').value+' ';

    $("PaymentBalloonDetails").innerHTML = "<p align=\"center\"><br/><img src=\"/v2.0/images/spinner.gif\" /> Saving payment ... <br/><br/></p>";
    //PositionBalloon(x, y);
    GlobalCB("Finances.OnSetPayment", InvoiceID, x, y, date, amount, receipt, account);
}

function OnEnterKeyDown(event, command)
{
    if (event.keyCode==13) 
    { 
        if (command)
            eval(command);
        if (!document.all)
            event.preventDefault();
        else
            event.returnValue = false;
    }
   
}