var g_CurrentJumpPopup = null;
var g_HandleDocumentBodyClick = null;
var g_ExportEventContextMenu = null;

// IE debug
//debugger

kwiz_cal_InitExportEventContextMenu();

function kwiz_cal_InitExportEventContextMenu()
{
	document.body.onmousedown = kwiz_cal_ContextMouseDown;
}

function kwiz_cal_ContextMouseDown(event)
{
	// IE is evil and doesn't pass the event object
	if (event == null)
		event = window.event;
    
	// we assume we have a standards compliant browser, but check if we have IE
	var target = event.target != null ? event.target : event.srcElement;

	// only show the context menu if the right mouse button is pressed
	//   and a hyperlink has been clicked (the code can be made more selective)
	if(target.id)
	{
	    var tmpStr = "kwiz_a_exportevent";
	    if (target.id.toLowerCase().substr(0, tmpStr.length) != tmpStr)
	    {
	        if (g_ExportEventContextMenu != null)
	            kwiz_cal_HideExportEventContextMenu(g_ExportEventContextMenu);
        }
	} else {
        if (g_ExportEventContextMenu != null)
	        kwiz_cal_HideExportEventContextMenu(g_ExportEventContextMenu);
    }
}

var g_WPQ = "";
var g_DragObj = null;
var g_MouseX, g_MouseY, g_MouseButton;
var scrollX = 0, scrollY = 0;       // window scroll offset
var x = null; x_old = null;         // selected column
var y = null; y_old = null;         // selected row
var dropbox = new Array();          // dropbox array
var droptarget = new Array();       // droptarget array
var g_Dragged = false;              // used to cancel onclick for FF/Chrome/Safari after dragged

// register onLoad event in C# code to call this method
function kwiz_cal_DragDropOnLoad(q)
{
    g_WPQ = q;

	// attach onscroll event (needed for recalculating table cells positions)
	window.onscroll = kwiz_cal_Scroll;
	
	if(browseris.ie || browseris.safari)
	{
	    kwiz_cal_Calculate_Cells();
	    
	    // disable text selection for ie, safari
	    document.onselectstart = function(event) {return false};
	}
	else
	{
        // firefox does not execute this function when assigning to onscroll event, but IE & Chrome do
	    kwiz_cal_Scroll(); 
	    
	    // disable text selection for firefox
	    if (typeof document.body.style.MozUserSelect != "undefined") 
	        document.body.style.MozUserSelect = "none";
	}
}

// calculate table colums and rows offset (cells dimensions) 
function kwiz_cal_Calculate_Cells(){
	// define inner function to calculate left and top object offset
	var offset = function(box, type){
									var oLeft = 0 - scrollX; // define offset left (take care of scroll position)
									var oTop  = 0 - scrollY; // define offset top (take care od scroll position)
									var box_old = box;       // remember box object
									// loop to the root element and return Y offsets for the box
									do {oLeft += box.offsetLeft; oTop += box.offsetTop} while (box = box.offsetParent);
									if (type == 'left') return oLeft;
									else                return (oTop + box_old.offsetHeight);
								}
	// define offset, box (for table and table cell) and counters
	var i, j;
	// get all tables inside div with id=drag
	var tbl = document.getElementById('KWizCom_CalendarTable' + g_WPQ);
	if (tbl == null) return;
    
	// collect table rows and initialize height of table rows
	var tr = tbl.getElementsByTagName('tr');
	var k = 0; k_old = 0;
	for (i=1; i<tr.length; i++)
	{
	    var td = tr[i].getElementsByTagName('td');
	    if (td.length > 0)
	    {
	        if (td[0].className == 'ms-cal-weekempty')
	        {
	            dropbox[k] = new Array();
	            droptarget[k] = new Array();
	            k_old = k;
	            var m = 0;
	            for (j=1; j<td.length; j++)
	            {
	                 var dropboxdate = td[j].getAttribute('dropboxdate');
	                 var dropboxindex = td[j].getAttribute('dropboxindex');
	                 if (dropboxdate != null)
	                 {
	                    dropbox[k][m] = new Object();
	                    dropbox[k][m].y = offset(td[j], 'top');
	                    dropbox[k][m].x = offset(td[j], 'left');
	                    dropbox[k][m].width = td[j].offsetWidth;
	                    dropbox[k][m].date = dropboxdate;
	                    dropbox[k][m].index = dropboxindex;
		                m++;
		            }
		        }
		        k++;
	        } 
	        else if (td[0].className == 'ms-cal-week' || td[0].className == 'ms-cal-weekB')
	        {
	            for (j=1; j<td.length; j++)
	            {
	                var droptargetdate = td[j].getAttribute('droptargetdate');
	                if (droptargetdate != null)
	                {
	                    for(var n=0; n<dropbox[k_old].length; n++)
	                    {
	                        if(dropbox[k_old][n].date == droptargetdate)
	                        {
	                            if (droptarget[k_old][n] == null)
	                            {
	                                droptarget[k_old][n] = new Array();
	                                droptarget[k_old][n].push(td[j]);
	                            }
	                            break;
	                        }
	                    }
	                }
	            }
	        }
	    }
	}
	
	// calculate dropbox height
	for(i=0; i<dropbox.length; i++)
	{
	    for(j=0; j<dropbox[i].length; j++)
	    {
	        if (i == dropbox.length - 1)
	            dropbox[i][j].height = tbl.offsetHeight + dropbox[0][j].y - dropbox[i][j].y;
	        else
	            dropbox[i][j].height = dropbox[i+1][j].y - dropbox[i][j].y;
	    }
	}
	
}

// take care of scroll position
function kwiz_cal_Scroll(event)
{
	// Netscape compliant
  if (typeof(window.pageYOffset) == 'number'){
    scrollY = window.pageYOffset;
    scrollX = window.pageXOffset;
  }
  // DOM compliant
  else if (document.body && (document.body.scrollLeft || document.body.scrollTop)){
    scrollY = document.body.scrollTop;
    scrollX = document.body.scrollLeft;
  }
  // IE6 standards compliant mode
  else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)){
    scrollY = document.documentElement.scrollTop;
    scrollX = document.documentElement.scrollLeft;
  }
	// recalculate table cells because table was scrolled 
	kwiz_cal_Calculate_Cells();
}


// function sets current column / row (variables x and y)
function kwiz_cal_Set_XY(event)
{
    // reset to original if mouse if out of calendar
    var i_len = dropbox.length;
    var j_len = dropbox[0].length;
    if ((event.clientX < dropbox[0][0].x) || (event.clientY < dropbox[0][0].y) || (event.clientX > (dropbox[i_len - 1][j_len - 1].x + dropbox[i_len - 1][j_len - 1].width)) || (event.clientY > (dropbox[i_len - 1][j_len - 1].y + dropbox[i_len - 1][j_len - 1].height)))
    {
        x = null;
        y = null;
        return;
    }
    
    for(i=0; i<dropbox.length; i++)
    {
        for(j=0; j<dropbox[0].length; j++)
        {
	        // if position is inside dropbox
	        if ((dropbox[i][j].x < event.clientX) && (event.clientX < (dropbox[i][j].x + dropbox[i][j].width)) &&(dropbox[i][j].y < event.clientY) && (event.clientY < (dropbox[i][j].y + dropbox[i][j].height)))
	        {
		        // set current cell position for X and Y
                x = j;
                y = i;
	        }
	    }
	}
}

function kwiz_cal_ItemMouseDown(obj, event)
{
	// define event (cross browser)
	if (event == null)
		event = window.event;

	// set reference to the dragable object
	g_DragObj = obj;
	var index = obj.getAttribute('dragindex');
	if (index == null)
	{
	    obj.setAttribute('dragindex', obj.parentNode.getAttribute('dragindex'));
	}
	
	// set current mouse position
	g_MouseX = event.clientX;
	g_MouseY = event.clientY;
	// and pressed mouse button
	if (event.which) g_MouseButton = event.which;
	else           g_MouseButton = event.button;
	// activate onmousemove and onmouseup on document level
	// if left mouse button is pressed
	if (g_MouseButton == 1){
		document.onmousemove = kwiz_cal_ItemMouseMove;
		document.onmouseup   = kwiz_cal_ItemMouseUp;
	}
	// set x, and y variables (columns and rows)
	kwiz_cal_Set_XY(event);
	// disable text selection
	return false;
}

function kwiz_cal_ItemMouseUp(event)
{
    try
    {
	    // reset left and top styles
	    g_DragObj.style.left = 0;
	    g_DragObj.style.top  = 0;
    	
	    // if object was dropped inside table then place it to the new location
	    if((x != null) && (y != null))
        {
	        if(droptarget[y][x].length > 0)
	        {
	            droptarget[y][x][0].style.backgroundColor = '';

	            // update backend item
	            var webUrl = g_DragObj.getAttribute('weburl');
	            var listId = g_DragObj.getAttribute('parentlistid');
	            var itemId = g_DragObj.getAttribute('itemid');
	            var startDate = new Date(g_DragObj.getAttribute('internalstartdate'));
	            var endDate = new Date(g_DragObj.getAttribute('internalenddate'));
	            var eventDate = new Date(g_DragObj.getAttribute('eventdate'));
	            var dragindex = g_DragObj.getAttribute('dragindex');
	            var dropindex = dropbox[y][x].index;
	            var days = dropindex - dragindex;
        	    
	            if (days != 0)
	            {
	                startDate.setDate(startDate.getDate() + days);
	                endDate.setDate(endDate.getDate() + days);
                    eventDate.setDate(eventDate.getDate() + days);
                    
                    if(KSCP_UpdateEventOnDragDrop(webUrl, listId, itemId, startDate, endDate))
                    {
                        // append/insert if dropping in last TD
                        var targetClassName = droptarget[y][x][0].className;
                        if(targetClassName == 'ms-cal-nodataBtm2' || targetClassName == 'ms-cal-noworkitem2B' || targetClassName == 'ms-cal-workitem2B')
                        {
                            var length = droptarget[y][x][0].childNodes.length;
                            if(length > 0)
                            {
                                var lastChild = droptarget[y][x][0].childNodes[length - 1];
                                if(lastChild.tagName.toLowerCase() == "table")
                                {
                                    droptarget[y][x][0].insertBefore(g_DragObj, lastChild);
                                }
                                else
                                {
                                     droptarget[y][x][0].appendChild(g_DragObj);
                                }                               
                            }
                            else
                            {
                                droptarget[y][x][0].appendChild(g_DragObj);
                            }
                        }
                        else
                        {
                            droptarget[y][x][0].appendChild(g_DragObj);
                        }
                        
                        if(browseris.ie)
                        {
                            // change each item height to fit the cell. only IE needs this adjustment
                            var length = droptarget[y][x][0].childNodes.length;
                            if (length > 1)
                            {
                                for(i=0; i<length;i++)
                                {
                                    droptarget[y][x][0].childNodes[i].style.height = 1/length;
                                }
                            }
                        }
                        g_DragObj.setAttribute('dragindex', dropbox[y][x].index);
                        g_DragObj.setAttribute('internalstartdate', startDate.toLocaleString());
                        g_DragObj.setAttribute('internalenddate', endDate.toLocaleString());
                        g_DragObj.setAttribute('eventdate', eventDate.toLocaleDateString());
                        var tds = g_DragObj.getElementsByTagName('td');
                        for(i=0; i<tds.length; i++)
                        {
                            var sTarget = tds[i].getAttribute('target');
                            var sTargetData = sTarget.split("|");
                            tds[i].setAttribute('target', sTargetData[0] + "|" + eventDate.toLocaleDateString());
                            break;
                        }
                        droptarget[y][x][0].onclick = null;
	                }
        	        
	                // onclick will not be triggered in IE if dropbox is different from drag box
	                if (browseris.ie)
	                {
	                    if (g_Dragged)
	                        g_Dragged = false;
	                }
	            }
	        }
	    }
    	
	    // detach onmousemove and onmouseup events
	    document.onmousemove = null;
	    document.onmouseup   = null;
	    // recalculate table cells because cell content could change row dimensions 
	    kwiz_cal_Calculate_Cells();
    }
    catch (e)
    {
    }
}

function kwiz_cal_ItemMouseMove(event)
{
    try 
    {
	    // define event (FF & IE)
	    if (event == null)
		    event = window.event;
	    // set left and top values for dragable element
	    g_DragObj.style.left = (event.clientX - g_MouseX) + "px";
	    g_DragObj.style.top  = (event.clientY - g_MouseY) + "px";
    	
	    // set x, and y
	    kwiz_cal_Set_XY(event);
	    // if new location is inside table and new location is different then old location
	    // set background colors for previous and new table cell
	    if ((x != x_old || y != y_old)){
		    // set cell color
		    if(x_old != null && y_old != null)
		    {
		        if(droptarget[y_old][x_old].length > 0)
		            droptarget[y_old][x_old][0].style.backgroundColor = '';
		    }
		    if(x != null && y != null)
		    {
		        if(droptarget[y][x].length > 0)
		            droptarget[y][x][0].style.backgroundColor = 'skyblue';
		    }
		    // remember current position (for column and row)
		    x_old = x; y_old = y;
	    }
    	
	    //if (!browseris.ie)
	        g_Dragged = true;
	} 
	catch (e)
	{
	}
	   
	return false;	
}

function KSCP_UpdateEventOnDragDrop(webUrl, listId, itemId, startDate, endDate)
{
	Url = webUrl + "/_vti_bin/Lists.asmx";
	HttpRequest = null;
	LastReadyStatus = -1;

    var Data = '<?xml version=\"1.0\" encoding=\"utf-8\"?>';
        Data += '<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">';
        Data += '<soap:Header xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"/>';
        Data += '<soap:Body>';
        Data += '<UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">';
        Data += '<listName>' + listId + '</listName><updates><Batch>';
        Data += '<Method ID="1" Cmd="Update"><Field Name="ID">' + itemId + '</Field><Field Name="EventDate">' + KSCP_ToISO8601DateTimeString(startDate) + '</Field><Field Name="EndDate">' + KSCP_ToISO8601DateTimeString(endDate) + '</Field></Method>';
        Data += '</Batch></updates></UpdateListItems></soap:Body></soap:Envelope>';    

	return KSCP_SendHttpRequest(Url, Data);
	
    function KSCP_ToISO8601DateTimeString(date) 
    {        
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();

        if (month <= 9) month = "0" + month;
        if (day <= 9) day = "0" + day;
        if (hour <= 9) hour = "0" + hour;
        if (minute <= 9) minute = "0" + minute;
        if (second <= 9) second = "0" + second;
        
        return year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second + "Z";
    }
    
    function KSCP_ToISO8601DateTimeStringTZ(date) 
    {        
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        
        if (month < 10) month = "0" + month;
        if (day < 10) day = "0" + day;
        if (hour < 10) hour = "0" + hour;
        if (minute < 10) minute = "0" + minute;
        if (second < 10) second = "0" + second;
        
        var timezone = (date.getTimezoneOffset() < 0 ? "-" : "+") + (date.getTimezoneOffset() / 60 < 10 ? "0" : "") + (date.getTimezoneOffset() / 60) + ":00";
        return year + "-" + month + "-" + day + "T" + hour + ":" + minute + ":" + second + ".000" + timezone;
    }

	function KSCP_CreateXMLHttpRequestObject()
	{
		try
		{
			var httpRequest = null;
			if( window.XMLHttpRequest ) // // Mozilla, Safari,...
			{
				var httpRequest = new XMLHttpRequest();
		    }
			else if( window.ActiveXObject )  // IE
			{
				var MSXML_XMLHTTP_PROGIDS = new Array(
								'Microsoft.XMLHTTP',
								'MSXML2.XMLHTTP.5.0',
								'MSXML2.XMLHTTP.4.0',
								'MSXML2.XMLHTTP.3.0',
								'MSXML2.XMLHTTP'
								);
				for (var i=0; i < MSXML_XMLHTTP_PROGIDS.length; i++)
				{
					httpRequest = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
					if( httpRequest != null )
					{
						break;
					}
				}
			}
			if(!httpRequest)
			{            
				alert("Failed to create the XmlHttpRequest Object");
			}  
			return httpRequest;
		}
		catch(e)
		{
		}
	}

	function KSCP_ReadyStateChanged()
	{
		var XMLHTTPREQUEST_COMPLETE = 4;
		var XMLHTTPREQUEST_OK = 200;
		var XMLHTTPREQUEST_REDIRECT = 302;
		var XMLEXPIRATION = 288;             
		var currentState = null;        
		var httpCode = null;
	    
		try
		{
			currentState = HttpRequest.readyState;           
		}
		catch(e)
		{
			//Handle exception here             
		}
	                
		try
		{       
			if ((currentState == 0 || currentState == XMLHTTPREQUEST_COMPLETE) && LastReadyStatus != XMLHTTPREQUEST_COMPLETE) 
			{                        
				try
				{
					httpCode = HttpRequest.status;                
				}
				catch(e)
				{                
					httpCode = 377;                
				}
	                      
				LastReadyStatus = currentState;    
	            
				if (httpCode == XMLHTTPREQUEST_OK)
				{   
					parent.innerHTML =  HttpRequest.responseText;
				}            
				else if (currentState != 0)
				{
				    if(httpCode != 0)   
					    alert("The operation failed with HTTP code " + httpCode);
				}
			}
			else
			{
				LastReadyStatus = currentState;   
			}        
		}
		catch(e)
		{        
			alert("The operation failed: " + e.description);
		}
	}

	function KSCP_SendHttpRequest(url, data)
	{   
		try
		{		   				
			HttpRequest = KSCP_CreateXMLHttpRequestObject();
			if (HttpRequest)
			{
			    HttpRequest.open("POST", url, true);
			    HttpRequest.onreadystatechange = KSCP_ReadyStateChanged;
			    HttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
			    HttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
			    HttpRequest.send(data);
			
			    return true;
			}
		}
		catch(e)   
		{
			alert("Failed to send XmlHttpRequest");
		}
		return false;
	}
}

function KSCP_MSOWebPartPage_OpenMenu(MenuToOpen,SourceElement)
{
	KSCP_MenuHtc_hide();
	g_HandleDocumentBodyClick = HandleDocumentBodyClick;
	
	HandleDocumentBodyClick = null;
	MSOWebPartPage_OpenMenu(MenuToOpen,SourceElement);
	
	window.setTimeout(function(){HandleDocumentBodyClick = g_HandleDocumentBodyClick;SetBodyEventHandlers(HandleDocumentBodyClick);}, 200);
}

function kwiz_EmptyFunction()
{
    return;
}
function kwiz_ClickDay(el, selDay, sWPQ)
{
    try
    {
        if(el == null)
            el = document.getElementById(selDay + sWPQ)
        var detailedTable = document.getElementById("kwiz_DetailedTable" + sWPQ)
        if(el.childNodes.length > 1)
        {
            if (el.childNodes[0].innerHTML == undefined)
            {
                detailedTable.innerHTML = el.childNodes[1].innerHTML; // Chrome/Firefox
            }            
            else
            {
                detailedTable.innerHTML = el.childNodes[0].innerHTML; // IE
            }
            detailedTable.style.display = "";
        }
    }
    catch(e)
    {
    }
}

function kwiz_cal_IframeReload (sWPQ, command, iframeWindow) 
{
    if((command == "") && (iframeWindow != null))
    {
        var addIframe = document.getElementById("KWizCom_CalendarAddIFrame" + sWPQ);
        try
        {
            addIframe.style.height = iframeWindow.document.height + 'px';
            addIframe.style.width = iframeWindow.document.width + 'px';
        }
        catch(e)
        {
            addIframe.style.height = iframeWindow.document.body.scrollHeight + 5 + 'px';
            addIframe.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
        }
   }
    if(command == "cancel")
    {
        document.getElementById("KWizCom_CalendarAddIFrame" + sWPQ).style.display = "none";
        document.getElementById("KWizCom_CalendarView" + sWPQ).style.display = "";
        try
        {
            document.getElementById("KWizCom_LegendArea" + sWPQ).style.display = "";
        }
        catch(e)
        {
        }
    }
    if(command == "added")
    {
        document.getElementById("KWizCom_CalendarAddIFrame" + sWPQ).style.display = "none";
        document.getElementById("KWizCom_CalendarView" + sWPQ).style.display = "";
        try
        {
            document.getElementById("KWizCom_LegendArea" + sWPQ).style.display = "";
        }
        catch(e)
        {
        }
	    var parent = document.getElementById("WebPart" + sWPQ);
	    if((parent != null) && (parent.isasync == true))
	    {
		    kwiz_cal_FormatQueryString(sWPQ);
		    var tmp = new KSCP_RenderCalendar(parent, sWPQ);
	    }
	    else
	    {
		    document.getElementById("ms-cal-hidedaysof" + sWPQ).form.submit();
	    }
    }
}

function kwiz_cal_AddNewItem(sURL, sTarget, sWPQ)
{
    if(sTarget == "_frame")
    {
        document.getElementById("KWizCom_CalendarView" + sWPQ).style.display = "none";
        try
        {
            document.getElementById("KWizCom_LegendArea" + sWPQ).style.display = "none";
        }
        catch(e)
        {
        }
        var addIframe = document.getElementById("KWizCom_CalendarAddIFrame" + sWPQ);
        addIframe.src = sURL;
        addIframe.style.display = "";
    }
    else
    {
	    var ch=sURL.indexOf("?") >=0 ? "&" : "?";
	    var srcUrl=GetSource();
	    if (srcUrl !=null && srcUrl !="")
		    srcUrl=ch+"Source="+srcUrl;
	    var targetUrl = sURL + srcUrl;
 	    var win = window.open(targetUrl, sTarget);
    }
}
function KSCP_CreateJumpCalendarMenu(elm, yearDivId, monthDivId, buttDivId, startDateId, sWPQ, year, month)
{
	g_CurrentJumpPopup = CMenu("calendarmenu");
	g_CurrentJumpPopup.setAttribute("CompactMode", "true");
	KSCP_CreateHtmlMenuItem(g_CurrentJumpPopup, document.getElementById(yearDivId + sWPQ).innerHTML);
	KSCP_CreateHtmlMenuItem(g_CurrentJumpPopup, document.getElementById(monthDivId + sWPQ).innerHTML);
	KSCP_CreateHtmlMenuItem(g_CurrentJumpPopup, document.getElementById(buttDivId + sWPQ).innerHTML);
	KSCP_OMenu(g_CurrentJumpPopup, elm, null, null, -1);
	var menuObject = g_CurrentJumpPopup._arrPopup == null ? g_CurrentJumpPopup : g_CurrentJumpPopup._arrPopup[0];
	var allTr = menuObject.getElementsByTagName("tr");
	for(var i = 0; i < allTr.length; i++)
	{
		if(allTr[i].getAttribute("type") == "option")
		{
			for(var ii = 0; ii < allTr[i].cells.length; ii++)
			{
				allTr[i].cells[ii].style.cursor = "auto";
			}
		}
	}

	/* year & month dropdown box doesn't display list in chrome/safari due to the following lines 	    
 	menuObject.onkeydown=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onmousedown=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onmouseover=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onmouseout=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onclick=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onmouseover=function(){event.returnValue = false; event.cancelBubble = true; return false;};
    menuObject.onmouseout=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onmousedown=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	menuObject.onclick=function(){event.returnValue = false; event.cancelBubble = true; return false;};   
	menuObject.oncontextmenu=function(){event.returnValue = false; event.cancelBubble = true; return false;};
	*/
	
	menuObject.style.cursor="auto";
	setTimeout(KSCP_ClearTimeOutToHideMenu, 100);
}

function KSCP_FindFieldValue(fname, xmlObj)
{
	this.caption = "";
	this.value = "";
	for(var i = 0; i < xmlObj.childNodes.length; i++)
	{
		if(xmlObj.childNodes[i].getAttribute("internalname") == fname)
		{
			this.caption = xmlObj.childNodes[i].getAttribute("fieldname");
			this.value = xmlObj.childNodes[i].getAttribute("fieldvalue");
			break;
		}
	}
}

function KSCP_MakeID(oMaster, nLevel, nIndex)
{
	return oMaster._wzPrefixID+"_"+nLevel+"_"+nIndex;
}
function KSCP_CreateMenuOption(oMaster, oRow, oNode, wzID, wzHtml, isMenuStructure)
{
	var oIcon=document.createElement("td");
	var oLabel=document.createElement("td");
	var oAccKey=document.createElement("td");
	var oArrow=document.createElement("td");
	if(isMenuStructure != false)
		oRow.appendChild(oIcon);
	oRow.appendChild(oLabel);
	if(isMenuStructure != false)
		oRow.appendChild(oAccKey);
	if(isMenuStructure != false)
		oRow.appendChild(oArrow);
	if (oMaster._fLargeIconMode)
		oIcon.className=!oMaster._fIsRtL ? "ms-MenuUIIconLarge" : "ms-MenuUIIconRtlLarge";
	else
		oIcon.className=!oMaster._fIsRtL ? "ms-MenuUIIcon" : "ms-MenuUIIconRtL";
	oIcon.align="center";
	if(isMenuStructure != false)
	{
		if (oMaster._fCompactItemsWithoutIcons && !oNode.getAttribute("iconSrc"))
			oLabel.className=!oMaster._fIsRtL ? "ms-MenuUILabelCompact" : "ms-MenuUILabelCompactRtl";
		else
			oLabel.className=!oMaster._fIsRtL ? "ms-MenuUILabel" : "ms-MenuUILabelRtL";
		oAccKey.className="ms-MenuUIAccessKey";
		oArrow.className="ms-MenuUISubmenuArrow";
		if (!oMaster._fLargeIconMode)
		{
			oLabel.noWrap=true;
		}
		oIcon.noWrap=true;
		oAccKey.noWrap=true;
		oArrow.noWrap=true;
		oLabel.id=oNode.id;
		if (!wzHtml) wzHtml=oNode.innerHTML;
		if (oNode.getAttribute("enabled")=="false")
		{
			oRow.disabled=true;
			oLabel.className+=" ms-MenuUIItemTableCellDisabled";
		}
		var wzIconSrc=null, wzIconAlt=null;
		if (oNode.getAttribute("checked")=="true")
			{
			wzIconSrc=oMaster._wzChkMrkPath;
			wzIconAlt="*";
			}
		else
			{
			wzIconSrc=KSCP_EvalAttributeValue(oNode, "iconSrc", "iconScript");
			wzIconAlt=oNode.getAttribute("iconAltText");
			}
		var innerHtml=wzHtml;
		var sText=KSCP_EvalAttributeValue(oNode, "text", "textScript");
		var sDescription=KSCP_EvalAttributeValue(oNode, "description", "descriptionScript");
		var oMenuItemBody=document.createElement("div");
		if (sDescription !=null && oMaster._fLargeIconMode)
		{
			var oBold=document.createElement("B");
			var oTextSpan=document.createElement("SPAN");
			var oTextNode=document.createTextNode(sText);
			var oBr=document.createElement("BR");
			var oDescSpan=document.createElement("SPAN");
			var oDescNode=document.createTextNode(sDescription);
			oTextSpan.setAttribute("style","white-space: nowrap;");
			oDescSpan.className="ms-menuitemdescription";
			oMenuItemBody.appendChild(oBold);
			oBold.appendChild(oTextSpan);
			oTextSpan.appendChild(oTextNode);
			oMenuItemBody.appendChild(oBr);
			oMenuItemBody.appendChild(oDescSpan);
			oDescSpan.appendChild(oDescNode);
		}
		else if (sText !=null)
		{
			var oTextSpan=document.createElement("SPAN");
			var oTextNode=document.createTextNode(sText);
			oTextSpan.setAttribute("style","white-space: nowrap;");
			oMenuItemBody.appendChild(oTextSpan);
			oTextSpan.appendChild(oTextNode);
		}
		var htmlSpan=document.createElement("SPAN");
		htmlSpan.innerHTML=innerHtml;
		oMenuItemBody.appendChild(htmlSpan);
		if (wzIconSrc)
		{
			var oImg=document.createElement("IMG");
			SetImageSize(oMaster, oImg);
			var oImgLbl=document.createElement("LABEL");
			oIcon.appendChild(oImg);
			oLabel.appendChild(oImgLbl);
			var wzIconId=wzID+"_"+"ICON";
			oImg.id=wzIconId;
			oImg.src=wzIconSrc;
			if (wzIconAlt)
			{
				oImg.alt="";
				oImg.title="";
			}
			oImgLbl.htmlFor=wzIconId;
			oImgLbl.appendChild(oMenuItemBody);
		}
		else
		{
			if (browseris.nav || oMaster._fLargeIconMode)
			{
				var oImg=document.createElement("IMG");
				SetImageSize(oMaster, oImg);
				var oImgLbl=document.createElement("LABEL");
				oIcon.appendChild(oImg);
				oLabel.appendChild(oImgLbl);
				var wzIconId=wzID+"_"+"ICON";
				oImg.id=wzIconId;
				oImg.src="/_layouts/images/blank.gif";
				oImg.alt="";
				oImg.title="";
				oImgLbl.htmlFor=wzIconId;
				oImgLbl.appendChild(oMenuItemBody);
				if (oMaster._fLargeIconMode)
				{
					oImg.width=32;
					oImg.height=16;
				}
				else
				{
					oImg.width=16;
				}
			}
			else
			{
				oIcon.innerHTML="&nbsp;";
				oLabel.appendChild(oMenuItemBody);
			}
		}
		var wzAccKey=oNode.getAttribute("accessKeyText");
		if (wzAccKey) oAccKey.innerHTML=wzAccKey;
		KSCP_SetIType(oRow, "option");
	}
	else
	{
		oLabel.innerHTML = oNode.innerHTML;
	}
}

function KSCP_JumpDate( yearDivId, monthDivId, sWPQ, view_period, day, format)
{
	var menuObject = g_CurrentJumpPopup._arrPopup == null ? g_CurrentJumpPopup : g_CurrentJumpPopup._arrPopup[0];
	var yearSelect = KSCP_GetChildByTagAndId(menuObject, "select", "cb_" + yearDivId + sWPQ);
	var year = yearSelect.options[yearSelect.selectedIndex].value;
	var monthSelect = KSCP_GetChildByTagAndId(menuObject, "select", "cb_" + monthDivId + sWPQ);
	var month = monthSelect.options[monthSelect.selectedIndex].value;
	var date = format.replace(/year/gi, year).replace(/month/gi, month).replace(/day/gi, day);
	g_CurrentJumpPopup = null;
	kwiz_cal_MoveToViewDate(date, view_period, sWPQ);
	KSCP_MenuHtc_hide();
}

function KSCP_GetChildByTagAndId(parent, tagName, id)
{
	var elms = parent.getElementsByTagName(tagName);
	for(var i = 0; i < elms.length; i++)
	{
		if(elms[i].id == id)
			return elms[i];
	}
	return null;
}
function KSCP_CreateHtmlMenuItem(menu, html)
{
	var mi=KSCP_CAMOpt(menu, "", "", "");
	mi.onMenuClick = null;
	mi.innerHTML = html;
}
function KSCP_ShowLogin(logintype, sWPR, sWPQ, buttonToClick)
{
    var curWindow = window;
    if(window.parent != null)
    {
        curWindow = window.parent;
    }
    
	var retvalue = curWindow.showModalDialog('/_layouts/KWizCom_KSCP/ModalContainer.htm', '/_layouts/KWizCom_KSCP/LoginAs.aspx?logintype=' + logintype + '&wpq=' + sWPQ + "&uncheck=" + (buttonToClick != null ? "1" : "0"), 'dialogHeight: 320px; dialogWidth:600px;edge:Raised;center:Yes;help:No;scroll:No;unadorned:No;resizable:No;status:No;');
	if((retvalue == true) && (buttonToClick != null))
		document.getElementById(buttonToClick).click();
}

function KSCP_ExportData(logintype, sWPR)
{
	window.showModalDialog('/_layouts/KWizCom_KSCP/ModalContainer.htm', '/_layouts/KWizCom_KSCP/LoginAs.aspx?logintype=' + logintype, 'dialogHeight: 320px; dialogWidth:600px;edge:Raised;center:Yes;help:No;scroll:No;unadorned:No;resizable:No;status:No;');
}

function KSCP_RenderCalendar(parent, sWPQ, url, data, hidObj,  imageUrl)
{
	parent.isasync = true;
	if(url != null)
	{
		parent.url = url;
		parent.hidobj = hidObj;
		parent.data = data;
		parent.imageurl = imageUrl;
		parent.monthviewext = "";
		parent.gotodateext = "";
	}
	else
	{
		url = parent.url;
		data = parent.data;
		imageUrl = parent.imageurl;
	}
	url = parent.url + parent.hidobj.value;
	
	Parent = parent;
	Url = url;
	Data = data;
	HttpRequest = null;
	LastReadyStatus = -1;
	var headObj = KSCP_GetChildByTagAndId(parent, "div", "navigationHeaderButonsDiv");
	if(headObj == null)
		parent.innerHTML = "<table border='0' class='ms-cal-header' cellspacing='15' cellpadding='15' width='100%' height='100%'><tr><td nowrap valign='middle'><img src='" + imageUrl + "'></td></tr></table>";
	else
	{
		headObj.style.height = headObj.offsetHeight;
		headObj.style.width = headObj.offsetWidth;
		headObj.innerHTML = "<img src='" + imageUrl + "'>";
	}
	KSCP_SendHttpRequest(Url, Data);
	function KSCP_CreateXMLHttpRequestObject()
	{
		try
		{
			var httpRequest = null;
			if( window.XMLHttpRequest ) // // Mozilla, Safari,...
			{
				var httpRequest = new XMLHttpRequest();
		}
			else if( window.ActiveXObject )  // IE
			{
				var MSXML_XMLHTTP_PROGIDS = new Array(
								'Microsoft.XMLHTTP',
								'MSXML2.XMLHTTP.5.0',
								'MSXML2.XMLHTTP.4.0',
								'MSXML2.XMLHTTP.3.0',
								'MSXML2.XMLHTTP'
								);
				for (var i=0; i < MSXML_XMLHTTP_PROGIDS.length; i++)
				{
					httpRequest = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
					if( httpRequest != null )
					{
						break;
					}
				}
			}
			if(!httpRequest)
			{            
				alert("Failed to create the XmlHttpRequest Object");
			}  
			return httpRequest;
		}
		catch(e)
		{
		}
	}

	function KSCP_ReadyStateChanged()
	{
		var XMLHTTPREQUEST_COMPLETE = 4;
		var XMLHTTPREQUEST_OK = 200;
		var XMLHTTPREQUEST_REDIRECT = 302;
		var XMLEXPIRATION = 288;             
		var currentState = null;        
		var httpCode = null;
	    
		try
		{
			currentState = HttpRequest.readyState;           
		}
		catch(e)
		{
			//Handle exception here             
		}
	                
		try
		{        
			if ((currentState == 0 || currentState == XMLHTTPREQUEST_COMPLETE) && LastReadyStatus != XMLHTTPREQUEST_COMPLETE) 
			{                        
				try
				{
					httpCode = HttpRequest.status;                
				}
				catch(e)
				{                
					httpCode = 377;                
				}
	                      
				LastReadyStatus = currentState;    
	            
				if (httpCode == XMLHTTPREQUEST_OK)
				{   
					parent.innerHTML =  HttpRequest.responseText;
				}            
				else if (currentState != 0)
				{   
					alert("The operation failed with HTTP code " + httpCode);
				}
			}
			else
			{
				LastReadyStatus = currentState;   
			}        
		}
		catch(e)
		{        
			alert("The operation failed: " + e.description);
		}
	}

	function KSCP_SendHttpRequest(url, data)
	{   
		try
		{		   				
			HttpRequest = KSCP_CreateXMLHttpRequestObject();
			HttpRequest.open("POST", url, true);
			HttpRequest.onreadystatechange = KSCP_ReadyStateChanged;
			HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			HttpRequest.send(data);
		}
		catch(e)   
		{
			alert("Failed to send XmlHttpRequest");
		}
	}
}

function kwiz_cal_FormatQueryString(q)
{
	var parent = document.getElementById("WebPart" + q);
	var urlExt = "&ms-cal-startdate" + q + "=" + document.getElementById("ms-cal-startdate" + q).value;
	urlExt += "&ms-cal-viewperiod" + q + "=" + document.getElementById("ms-cal-viewperiod" + q).value;
	urlExt += "&ms-cal-expandedweek" + q + "=" + document.getElementById("ms-cal-expandedweek" + q).value;
	urlExt += "&ms-cal-viewstyle" + q + "=" + document.getElementById("ms-cal-viewstyle" + q).value;
	urlExt += "&ms-cal-hidedaysof" + q + "=" + document.getElementById("ms-cal-hidedaysof" + q).value;
	urlExt += "&ms-cal-timezone" + q + "=" + document.getElementById("ms-cal-timezone" + q).value;
	urlExt += "&ms-cal-selectedcategories" + q + "=" + document.getElementById("ms-cal-selectedcategories" + q).value;
	urlExt += "&ms-cal-selectedcustomview" + q + "=" + document.getElementById("ms-cal-selectedcustomview" + q).value;
	urlExt += "&ms-cal-sortfields" + q + "=" + document.getElementById("ms-cal-sortfields" + q).value;
	parent.hidobj.value = urlExt;
}
function kwiz_cal_MoveToHideDaysOf(val, q)
{
	var parent = document.getElementById("WebPart" + q);
	document.getElementById("ms-cal-hidedaysof" + q).value = val;
	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-hidedaysof" + q).form.submit();
	}
}
function kwiz_cal_SelectTimeZone(val, q)
{
	var parent = document.getElementById("WebPart" + q);
	document.getElementById("ms-cal-timezone" + q).value = val;
	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-timezone" + q).form.submit();
	}
}

function kwiz_cal_SelectCustomView(strdate, view_type, q, val)
{
    kwiz_cal_MoveToViewDate(strdate, view_type, q, val);	
}

function kwiz_cal_DisplayExportEventContextMenu(webUrl, listId, itemId, q, event)
{
    // IE may not pass the event object
    if (event == null)
		event = window.event;

	// we assume we have a standards compliant browser, but check if we have IE
	var target = event.target != null ? event.target : event.srcElement;
	
    var menu = document.getElementById("kwiz_div_ContextMenu" + q);
    if (menu != null)
    {
        g_ExportEventContextMenu = menu;
        var menuitem = document.getElementById("kwiz_a_ExportEvent" + q);
        if (menuitem != null)
        {
            menuitem.href = webUrl + "/_vti_bin/owssvr.dll?CS=109&Cmd=Display&List=" + listId + "&CacheControl=1&ID=" + itemId + "&Using=event.ics";
		    
		    // document.body.scrollTop does not work in IE
		    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
			    document.documentElement.scrollTop;
		    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
			    document.documentElement.scrollLeft;

		    // hide the menu first to avoid an "up-then-over" visual effect
		    menu.style.display = "none";
		    menu.style.left = event.clientX + scrollLeft + 'px';
            menu.style.top = event.clientY + scrollTop + 'px';
            menu.style.display = "block";
            
            SetBodyEventHandlers(kwiz_cal_HandleDocumentBodyClick);
	
	        // hide tooptip if it exists
	        if (g_KSCP_menuHtc_lastMenu != null)
	    	        KSCP_HideMenu(g_KSCP_menuHtc_lastMenu);
        }
    }
}

function kwiz_cal_QuickEvent(q, year, month, day, lists, event)
{
    // for monthly view
    
    // IE may not pass the event object
    if (event == null)
		event = window.event;

	// we assume we have a standards compliant browser, but check if we have IE
	var target = event.target != null ? event.target : event.srcElement;
		
    var div = document.getElementById("kwiz_div_QuickEvent" + q);
    var frame = document.getElementById("kwiz_iframe_QuickEvent" + q);
    var src = frame.src;
    var tz = document.getElementById("ms-cal-timezone" + q).value
    var qs = "?wpq=" + q + "&year=" + year + "&month=" + month + "&day=" + day + "&tz=" + tz + "&lists=" + lists;
    
    if (src.indexOf(qs) > 0)
    {
        if (div.style.display != "none")
        {
            div.style.display = "none";
            return;
        }
    }
    else
    {
        frame.src = "/_layouts/KWizCom_KSCP/QuickCreateItem.aspx" + qs;
    }
    
    // document.body.scrollTop does not work in IE
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;

    div.style.left = event.clientX + scrollLeft + 'px';
    div.style.top = event.clientY + scrollTop + 'px';
    div.style.display = "block";

}


function kwiz_cal_QuickEventDaily(q, year, month, day, hour, minute, lists, event)
{
    // for weekly/daily view
    
    // IE may not pass the event object
    if (event == null)
		event = window.event;

	// we assume we have a standards compliant browser, but check if we have IE
	var target = event.target != null ? event.target : event.srcElement;
		
    var div = document.getElementById("kwiz_div_QuickEvent" + q);
    var frame = document.getElementById("kwiz_iframe_QuickEvent" + q);
    var src = frame.src;
    var tz = document.getElementById("ms-cal-timezone" + q).value
    var qs = "?wpq=" + q + "&year=" + year + "&month=" + month + "&day=" + day + "&hour=" + hour + "&minute=" + minute + "&tz=" + tz + "&lists=" + lists;
    
    if (src.indexOf(qs) > 0)
    {
        if (div.style.display != "none")
        {
            div.style.display = "none";
            return;
        }
    }
    else
    {
        frame.src = "/_layouts/KWizCom_KSCP/QuickCreateItemDaily.aspx" + qs;
    }
    
    // document.body.scrollTop does not work in IE
    var scrollTop = document.body.scrollTop ? document.body.scrollTop :
        document.documentElement.scrollTop;
    var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft :
        document.documentElement.scrollLeft;

    div.style.left = event.clientX + scrollLeft + 'px';
    div.style.top = event.clientY + scrollTop + 'px';
    div.style.display = "block";

}

function kwiz_cal_QuickEventCreateClick(q)
{
    // hide Quick Event page
    var div = document.getElementById('kwiz_div_QuickEvent' + q);
    if(div != null)
        div.style.display = 'none';
        
    // document.location.reload(true) <-- will display prompt
    // document.location.href = document.location.href; <-- no prompt in IE, however it switches to default view
    // the following statement works great!
    document.getElementById("ms-cal-viewstyle" + q).form.submit();
}

function kwiz_cal_HandleDocumentBodyClick(e)
{
    if (g_ExportEventContextMenu != null)
    {
        kwiz_cal_HideExportEventContextMenu(g_ExportEventContextMenu);
        g_ExportEventContextMenu = null;
	}
}

function kwiz_cal_HideExportEventContextMenu(obj)
{
    obj.style.display = "none";
}

// sort table view by clicking on column title
// - default: StartDate Asc
// - click on first time: Asc; second time: Desc; third time: back to default
function kwiz_cal_SortBy(field, q)
{
	var parent = document.getElementById("WebPart" + q);
	var el = document.getElementById("ms-cal-sortfields" + q);
	var prevVal = el.value; 
	if(prevVal.length > 0)
	{
        if(prevVal.indexOf(";") > 0)
        {
	        var vals = prevVal.split(";");
            if(vals[0].length == 0 || vals[0] != field)
            {
                vals[0] = field;
                vals[1] = "1";
            }
            else
            {
                if(vals[1] == "1")
                    vals[1] = "2";
                else if(vals[1] == "2")
                    vals[1] = "";
                else
                    vals[1] = "1";
            }
            
            if (vals[0] == "" || vals[1] == "")
                el.value = "";
            else
                el.value = vals[0] + ";" + vals[1];
        }
        else
        {
            el.value = field + ";1";
        }     
    }
    else
    {
        el.value = field + ";1";
    }

	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-sortfields" + q).form.submit();
	}
}

function kwiz_cal_ShowCategory(val, q)
{
	var parent = document.getElementById("WebPart" + q);
	var el = document.getElementById("ms-cal-selectedcategories" + q);
	var prevVal = el.value; 
	if((val.length > 0 && val != "All Categories") && (prevVal.length > 0))
	{
	    var res = "";
	    var vals = prevVal.split(";");
	    var found = false;
	    for(var i = 0; i < vals.length; i++)
	    {
	        if(vals[i].length == 0)
	            continue;
	            
	        if((found == false) && (vals[i] == val))
	        {
	            found = true;
	            continue;
	        }
	        
	        if(res.length > 0)
	        {
	            res += ";";
	        }
	        res += vals[i];
	    }
	    if(found == false)
	    {
	        if(res.length > 0)
	        {
	            res += ";";
	        }
	        res += val;
	    }
	    if(res != "")
	    {
	        el.value = res;
	    }
	    else
	    {
	        el.value = "All Categories";
	    }
	}
	else
	{
	    el.value = val;
	}
	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-selectedcategories" + q).form.submit();
	}
}

function kwiz_EnableTooltip(q)
{
    var stl = document.getElementById("ms-cal-viewstyle" + q).value;
    if(eval("g_EnableTooltip" + q) == true)
    {
        if((stl.toLowerCase() == "table") && (eval("g_EnableTableTooltip" + q) == false))
        {
            return false;
        }
        return true;
    }
    return false;
}
function kwiz_cal_MoveToViewStyle(view_style, q)
{
	var parent = document.getElementById("WebPart" + q);
	document.getElementById("ms-cal-viewstyle" + q).value = view_style;
	// switch from custom table to calendar view
	if (view_style.toLowerCase() == "calendar")
	{
	    var view_period = document.getElementById("ms-cal-viewperiod" + q).value;
	    if (view_period.toLowerCase() == "custom")
	    {
	        document.getElementById("ms-cal-viewperiod" + q).value = "Month";
	        var customview = document.getElementById("ms-cal-selectedcustomview" + q);
	        if (customview != null)
	        {
	            customview.value = -1;
	        } 
	        else 
	        {
	            kwiz_cal_AddHiddenInputField("ms-cal-selectedcustomview" + q, -1);
	        }
	        today = new Date();
	        firstday = new Date(today.getFullYear(), today.getMonth(), 1);
	        lastday = new Date(today.getFullYear(), today.getMonth()+1, 0);
		    var startdate = document.getElementById("ms-cal-startdate" + q);
		    if (startdate != null)
		    {
		        startdate.value = firstday.toDateString();
		    }
		    else
		    {
		        kwiz_cal_AddHiddenInputField("ms-cal-startdate" + q, firstday.toDateString());
		    }  
	    }
	} 
	else if (view_style.toLowerCase() == "table")	// switch from calendar to table view (default custom view may be set)
	{
	    var view_period = document.getElementById("ms-cal-viewperiod" + q).value;
	    if (view_period.toLowerCase() != "custom")
	    {
	        var customview = document.getElementById("ms-cal-selectedcustomview" + q);
	        if (customview != null)
	        {
	            customview.value = -1;
	        } 
	        else 
	        {
	            kwiz_cal_AddHiddenInputField("ms-cal-selectedcustomview" + q, -1);
	        }
	    }
	}

	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-viewstyle" + q).form.submit();
	}
}
function kwiz_cal_AddHiddenInputField(fieldName, fieldValue) 
{   
    var inputElement = document.createElement("input");
    inputElement.setAttributeNode(createHtmlAttribute("type", "hidden"));
    inputElement.setAttributeNode(createHtmlAttribute("name", fieldName));
    inputElement.setAttributeNode(createHtmlAttribute("value", fieldValue));
    document.forms[0].appendChild(inputElement);
    return;
}
function kwiz_cal_MoveToCastomDateDate(q)
{
    var from = document.getElementById("FromDateTimeFieldDate" + q).value;
    var to = document.getElementById("ToDateTimeFieldDate" + q).value;
    kwiz_cal_MoveToViewDate(from + "|" + to, "month", q);
}
function kwiz_cal_MoveToViewDate(strdate, view_type, q, val)
{
    /* added a new parameter val for custom view dropdown box.
       if it is omitted, the default value will set to -1, means
       that custom view will not take effort. */
    if (val === undefined)
    {
	    document.getElementById("ms-cal-selectedcustomview" + q).value = -1;
	}
    else
    {
	    document.getElementById("ms-cal-selectedcustomview" + q).value = val;
    }
    
	if(document.getElementById("ms-cal-intigwspscal" + q).value == 0)
	{
		var parent = document.getElementById("WebPart" + q);
		document.getElementById("ms-cal-startdate" + q).value = strdate;
		document.getElementById("ms-cal-viewperiod" + q).value = view_type;
		if((parent != null) && (parent.isasync == true))
		{
			kwiz_cal_FormatQueryString(q);
			var tmp = new KSCP_RenderCalendar(parent, q);
		}
		else
		{
			document.getElementById("ms-cal-viewperiod" + q).form.submit();
		}
	}
	else
	{
		MoveToViewDate(strdate, view_type);
	}
}


function kwiz_cal_GetMonthView(str, q)
{
	var parent = document.getElementById("WebPart" + q);
	document.getElementById("ms-cal-expandedweek" + q).value = str;
	if((parent != null) && (parent.isasync == true))
	{
		kwiz_cal_FormatQueryString(q);
		var tmp = new KSCP_RenderCalendar(parent, q);
	}
	else
	{
		document.getElementById("ms-cal-expandedweek" + q).form.submit();
	}
}

function  kwiz_cal_GoToLink(elm, sWPQ)
{
    //if(!browseris.ie)
    //{
        if(g_Dragged)
        {
            g_Dragged = false;
            return;
        }
    //}
    
    if(eval("g_EnableClick" + sWPQ) == false)
        return;
        
    var sTarget = elm.getAttribute("target");
    var sTargetData = sTarget.split("|");
    if(sTargetData[0] == "day")
    {
   	    kwiz_cal_MoveToViewDate(sTargetData[1], 'Day', sWPQ);
    	 return;
    }

	var href = elm.getAttribute("forhref");
	if(href == null)
		href = elm.getAttribute("href");
	if(href == null)
	{
		var tds = elm.getElementsByTagName("td");
		for(var i = 0; i < tds.length; i++)
		{
		    if(href != null)
		        return;
		    try
		    {
			    href = tds[i].getAttribute("href");;
			}
			catch(e)
			{
			}
		}
	}
	if(href == null)
        return;
        
	var ch=href.indexOf("?") >=0 ? "&" : "?";
	var srcUrl=GetSource();
	if (srcUrl !=null && srcUrl !="")
		srcUrl=ch+"Source="+srcUrl;
	var targetUrl = href + srcUrl;
 	var win = window.open(targetUrl, sTargetData[0]);
}
function kwiz_cal_ShowToolPane(id)
{
    try
    {
	    MSOTlPn_ShowToolPane2Wrapper('Edit','0',id);
	}
	catch(e)
	{
	    MSOTlPn_ShowToolPaneWrapper('1', '0', id);
	}
}

function kwiz_cal_TableView_GotoPage(direction, q)
{
    var header = document.getElementById('KWizCom_TableViewHeader' + q);
    if (header != null)
    {
        var pagesize = parseInt(header.getAttribute("pagesize"));
        if (pagesize > 0)
        {
            var numberofitems = parseInt(header.getAttribute("numberofitems"));
            var currentpage = parseInt(header.getAttribute("currentpage"));
            var maxpage = parseInt(header.getAttribute("maxpage"));
            var nextpage;
            var previouslink = document.getElementById('kwiz_a_PreviousPage' + q);
            var nextlink = document.getElementById('kwiz_a_NextPage' + q);
            
            if (direction == 'p')
            {
                if (currentpage <= 2)
                {
                    nextpage = 1;
                    kwiz_cal_TableView_DisableLink(previouslink, true);
                }
                else
                {
                    nextpage = currentpage - 1;
                    kwiz_cal_TableView_DisableLink(previouslink, false);
                }
                kwiz_cal_TableView_DisableLink(nextlink, false);
            }
            else
            {
                if (currentpage >= maxpage - 1)
                {
                    nextpage = maxpage;
                    kwiz_cal_TableView_DisableLink(nextlink, true);
                }
                else
                {
                    nextpage = currentpage + 1;
                    kwiz_cal_TableView_DisableLink(nextlink, false);
                }
                kwiz_cal_TableView_DisableLink(previouslink, false);
            }
            
            for(var i = 1; i <= numberofitems; i++)
            {
                var item = document.getElementById('KWizCom_TableViewItem' + q + '_' + i);
                if (item != null)
                {
                    if (i > ((nextpage - 1) * pagesize) && i <= (nextpage * pagesize))
                        item.style.display = '';
                    else
                        item.style.display = 'none';
                }
            }
            
            header.setAttribute("currentpage", nextpage +'');
        }
    }
}

function kwiz_cal_TableView_DisableLink(link, disabled)
{
    if(disabled)
    {
        link.className = "ms-link-disabled";
        link.setAttribute("href", "javascript:return false;");
    }
    else
    {
        link.className = "";
        link.setAttribute("href", link.getAttribute("href_back"));
    }
}

function kwiz_cal_Print_Expanded(q)
{
    /* this function is used for Calendar and Mini-Calendar */
	var disp_setting = "toolbar=no,location=no,directories=no,menubar=no,"; 
	disp_setting += "scrollbars=yes,width=650, height=600, left=100, top=25";

	var urlExt = "?print" + q + "=1" + "&ms-cal-expandedweek" + q + "=1111111";
	urlExt += "&ms-cal-startdate" + q + "=" + document.getElementById("ms-cal-startdate" + q).value;
	urlExt += "&ms-cal-viewperiod" + q + "=" + document.getElementById("ms-cal-viewperiod" + q).value;
	urlExt += "&ms-cal-viewstyle" + q + "=" + document.getElementById("ms-cal-viewstyle" + q).value;
	urlExt += "&ms-cal-hidedaysof" + q + "=" + document.getElementById("ms-cal-hidedaysof" + q).value;
	urlExt += "&ms-cal-timezone" + q + "=" + document.getElementById("ms-cal-timezone" + q).value;
	urlExt += "&ms-cal-selectedcategories" + q + "=" + document.getElementById("ms-cal-selectedcategories" + q).value;
	urlExt += "&ms-cal-selectedcustomview" + q + "=" + document.getElementById("ms-cal-selectedcustomview" + q).value;
	urlExt += "&ms-cal-sortfields" + q + "=" + document.getElementById("ms-cal-sortfields" + q).value;

    var qs = location.search;
    var url = location.href;
    if (qs.length > 0)
        url = url.substring(0, url.indexOf(qs));
	var winprint = window.open(url + urlExt,"print_expanded", disp_setting); 
}

function kwiz_cal_Print(q, action)
{

	var disp_setting="toolbar=no,location=no,directories=no,menubar=no,"; 
	disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25"; 
	var calendarView = document.getElementById("KWizCom_CalendarView" + q)
	
	var content_vlue = "";
	var title = document.getElementById("WebPartTitle" + q)
	content_vlue += "<table width=100%><tr>";
	var titleText = "Calendar Printing";
	if(title != null)
	{
	     content_vlue += "<TD style='WIDTH: 100%'>" +  title.innerHTML + "</TD>";
	     titleText = document.all ? title.innerText : title.textContent;
    }
    var navBar = KSCP_GetChildByTagAndId(calendarView, "div", "navigationHeaderButonsDiv")
    if(navBar != null)
    {
        content_vlue += "<td nowrap width=30%>" + (document.all ? navBar.innerText : navBar.textContent) + "</td>";
    }
	
	if(content_vlue != "<table width=100%><tr>")
	    content_vlue += "</tr></table>";
	content_vlue += "<TABLE class=ms-cal-gempty id=KWizCom_CalendarTableWPQ6  cellSpacing=0 cellPadding=0 width='100%' border=0>" + document.getElementById("KWizCom_CalendarTable" + q).innerHTML + "</TABLE>"; 
	var legent = document.getElementById("KWizCom_LegendArea" + q); 
	if(legent != null)
	    content_vlue += "<TABLE class=ms-calheader>" + legent.innerHTML + "</TABLE>";

	var docprint=window.open("","",disp_setting);
	docprint.document.open(); 
	docprint.document.write('<html><head><title>' + titleText + '</title>'); 
	for(var i = 0; i < document.styleSheets.length; i++)
	{
		docprint.document.write('<LINK href="' + document.styleSheets[i].href + '" rel=Stylesheet>');
	}

    docprint.document.write('</head><body onLoad="self.print();self.close();"><center>');          
	var re1 = new RegExp("onmouse", "ig");     
	var re2 = new RegExp("onclick", "ig");     
	var re3 = new RegExp("href", "ig");
	var re4 = new RegExp("DISPLAY: none; CURSOR", "ig");    
	docprint.document.write(content_vlue.replace(re1, "onmouse1").replace(re2, "onclick1").replace(re3, "href1").replace(re4, "DISPLAY: block; CURSOR"));        
	docprint.document.write('</center></body></html>'); 
	docprint.document.close();
	/* action - table view: no need to close parent window as it doesn't require interim page */
	if(action == '1')
	{
	    docprint.opener.close();
	}
	docprint.focus(); 
}

g_CurrentTooltipTimeout = null;
function  kwiz_cal_ItemMouseOver(elm, sWPQ, override)
{
    // added new parameter override, meaning that context menu will override tooltip
    //if(override != undefined && override != "")
    //    return;
    if(g_CurrentJumpPopup != null)
        return;
    elm.setAttribute("WPQ", sWPQ);
    if((eval("g_EnableClick" + sWPQ) == true) || (kwiz_EnableTooltip(sWPQ) == true))
        if(elm.getAttribute("bclassname") == null)
            elm.setAttribute("selclassname", elm.className);
        else
            elm.className = elm.getAttribute("bclassname") + " " + elm.getAttribute("bclassname") + "sel";
    if(kwiz_EnableTooltip(sWPQ) == false)
        return;
	if((elm != document.body.calttel) && (document.body.calttel != null))
		document.body.calttel.popup = null;
	document.body.calttel = elm;
	g_CurrentTooltipTimeout = window.setTimeout(function(){kwiz_cal_ShowTooltip(sWPQ);}, 500);
}
function  kwiz_cal_ItemMouseOut(elm)
{
    try
    {
        if(elm == null)
            elm = window.event.srcElement;
 //       if(g_KSCP_menuHtc_lastMenu == null)
  //          return;
        if(g_KSCP_menuHtc_lastMenu != null)
        {
            var oPopup=g_KSCP_menuHtc_lastMenu._arrPopup[0];

            if(oPopup.contains(window.event.toElement))
                return;
        }
        if(elm.getAttribute("bclassname") != null)
 	        elm.className = elm.getAttribute("bclassname");
        if((elm.getAttribute("WPQ") != null) && (kwiz_EnableTooltip(elm.getAttribute("WPQ")) == false))
            return;
	    elm.toElement = window.event.toElement;
	    window.clearTimeout(g_CurrentTooltipTimeout);
	    g_CurrentTooltipTimeout = null;
	    KSCP_SetTimeOutToHideMenu()
	 }
	 catch(e)
	 {
	 }
}

function KSCP_CMenu(wzID)
{
	var m=document.getElementById(wzID);
	if (m)
	{
		m._initialized=false;
		m._oContents=null;
		m.innerHTML="";
		return m;
	}
	m=document.createElement("MENU");
	if(!m)return null;
	if(wzID)m.id=wzID;
	m.className="ms-SrvMenuUI";
	AChld(document.body,m);
	return m;
}
function KSCP_CAMOpt(p,wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc)
{
	var mo=KSCP_CMOpt(wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc);
	if(!mo)return null;
	KSCP_AChld(p,mo);
	return mo;
}
function KSCP_CMOpt(wzText,wzAct,wzISrc,wzIAlt,wzISeq,wzDesc)
{
	var mo=KSCP_CMItm("option");
	if(!mo)return null;
	mo.setAttribute("text", wzText);
	mo.setAttribute("onMenuClick", wzAct);
	if (wzDesc)mo.setAttribute("description", wzDesc);
	KSCP_AImg(mo,wzISrc,wzIAlt);
	if(KSCP_FNEmpWz(wzISeq))mo.setAttribute("sequence",wzISeq);
	return mo;
}
function KSCP_CMItm(wzType)
{
	var mi=document.createElement("SPAN");
	if(!mi)return null;
	mi.setAttribute("type",wzType);
	return mi;
}
function KSCP_AImg(mi,wzISrc,wzIAlt)
{
	if(!mi)return;
	if(KSCP_FNEmpWz(wzISrc))mi.setAttribute("iconSrc",wzISrc);
	if(KSCP_FNEmpWz(wzIAlt))
		mi.setAttribute("iconAltText",wzIAlt);
	else
		mi.setAttribute("iconAltText","");
}
function KSCP_FNEmpWz(wz)
{
	return (wz&&wz!="");
}
function KSCP_AChld(p,c)
{
	if(p&&c)p.appendChild(c);
}
function KSCP_OMenu(m,r,fr,ft,yoff, isMenuStructure)
{
	if(typeof(m)=="string")m=document.getElementById(m);
	if(m)
		{
			KSCP_OMenuInt(m,r,fr,ft,yoff, isMenuStructure);
		}
	return false;
}
function KSCP_OMenuInt(m,r,fr,ft,yoff, isMenuStructure)
{
	if(m&&!KSCP_MenuHtc_isOpen(m)) KSCP_MenuHtc_show(m,r,fr,ft,yoff, isMenuStructure);
}
function KSCP_MenuHtc_isOpen(oMaster)
{
	if (!oMaster || !oMaster._initialized)
		return false;
	var result=KSCP_IsOpen(oMaster);
	return result;
}
function KSCP_MenuHtc_show(oMaster, oParent, fForceRefresh, fFlipTop, yOffset, isMenuStructure)
{
	if (!(browseris.ie55up || browseris.nav6up || browseris.safari125up))
		return false;
	MenuHtc_hide()
	KSCP_MenuHtc_hide();
	g_CurrentShownElement = oParent;
	KSCP_MenuHtc_init(oMaster);
	oMaster._oParent=oParent;
	oMaster._fIsRtL=KSCP_IsElementRtl(oMaster._oParent);
	KSCP_SetBodyEventHandlers(null);
	KSCP_AssureId(oParent);
	var result=KSCP_ShowRoot(oMaster, oParent, fForceRefresh, fFlipTop, yOffset, isMenuStructure);
	KSCP_NavigateToMenu(oMaster);
	g_KSCP_menuHtc_lastMenu=oMaster;
	if (browseris.ie)
	{
		if (window.event !=null)
			window.event.cancelBubble=true;
	}
	return false;
}
function KSCP_GetIType(oItem)
{
	return oItem ? oItem.getAttribute("type") : null;
}
function KSCP_NavigateToMenu(oMaster)
{
	var oMenu=oMaster._arrPopup[oMaster._nLevel].firstChild;
	KSCP_AssureId(oMenu);
	try
	{		
		var oFirstItem=oMenu.firstChild.firstChild.firstChild;		
		oFirstItem.tabIndex=0;
		if (oFirstItem.setActive !=null)
			oFirstItem.setActive();
		else if (oFirstItem.focus !=null)
			oFirstItem.focus();
	}
	catch (e)
	{
	}
}
function KSCP_ShowRoot(oMaster, oParent, fForceRefresh, fFlipTop, yOffset, isMenuStructure)
{
	KSCP_UpdateLevel(oMaster, 0);
	if (fForceRefresh)
		{
		oMaster._oContents=null;
		oMaster._oRoot=null;
		oMaster._nLevel=0;
		oMaster._arrPopup=new Array();
		oMaster._arrSelected=new Array();
		}
	else
		{
		oMaster._oRoot=oMaster._oContents;
		}
	var y=0;
	if (oParent) y+=oParent.offsetHeight;
	if (browseris.safari)
	{
		if (oParent.tagName=="TR" && oParent.childNodes.length > 1) // 0 -> 1
		{
			y+=(oParent.childNodes[1].offsetTop+oParent.childNodes[1].offsetHeight
				- oParent.offsetTop);
		}
	}
	if (yOffset) y+=yOffset;
	fFlipTop=fFlipTop !=false;
	KSCP_MenuHtcInternal_Show(oMaster, oParent, y, fFlipTop, isMenuStructure);
}
function KSCP_AssureId(obj)
{
	if (obj.id==null || obj.id=="")
		obj.id="msomenuid"+KSCP_GetUniqueNumber();
	return obj.id;
}
function KSCP_FIsIType(oItem, wzType)
{
	return KSCP_FIStringEquals(KSCP_GetIType(oItem), wzType);
}
function KSCP_FIStringEquals(wzX, wzY)
{
	return wzX !=null && wzY !=null && wzX.toLowerCase()==wzY.toLowerCase();
}
function KSCP_FIsIHidden(oItem)
{
	if (oItem)
	{
		var hiddenFunc=oItem.getAttribute("hidden");
		if (!hiddenFunc) return false;
		return eval(hiddenFunc);
	}
	else
		return false;
}
function KSCP_FixUpMenuStructure(oMaster)
{
	var menuNodes=oMaster._oRoot.childNodes;
	var lastGroupId=null;
	var lastMenuSeparatorRow=null;
	for (var nIndex=0; nIndex < menuNodes.length; nIndex++)
	{
		var menuRow=menuNodes[nIndex];
		if (menuRow.nodeType !=1)
			continue;
		var deleteRow=false;
		var displayNone=menuRow.style !=null && menuRow.style.display=='none';
		var jsHidden=KSCP_FIsIHidden(menuRow);
		if (displayNone || jsHidden)
		{
			deleteRow=true;
		}
		else if (KSCP_FIsIType(menuRow, "separator"))
		{
			if (lastMenuSeparatorRow !=null || nIndex==0)
				deleteRow=true;
			else
				lastMenuSeparatorRow=menuRow;
		}
		else
		{
			var cGroupId=menuRow.getAttribute("menuGroupId");
			if (cGroupId !=lastGroupId &&
				lastMenuSeparatorRow==null &&
				nIndex !=0)
			{
				var lastMenuSeparatorRow=document.createElement("ie:menuitem");
				lastMenuSeparatorRow.setAttribute("type","separator");
				oMaster._oRoot.insertBefore(lastMenuSeparatorRow,menuRow);
			}
			else if (KSCP_FIsIType(menuRow, "submenu") && lastMenuSeparatorRow !=null)
			{
				menuRow.parentNode.removeChild(lastMenuSeparatorRow);
				lastMenuSeparatorRow=null;
			}
			else
			{
				lastMenuSeparatorRow=null;
			}
			lastGroupId=cGroupId;
		}
		if (deleteRow)
		{
			menuRow.parentNode.removeChild(menuRow);
			nIndex--;
		}
	}
	if(lastMenuSeparatorRow !=null)
		lastMenuSeparatorRow.parentNode.removeChild(lastMenuSeparatorRow);
}
function KSCP_PrepContents(oMaster, isMenuStructure)
{
	oMaster._fLargeIconMode=(oMaster.getAttribute("largeIconMode")=="true");
	oMaster._fCompactItemsWithoutIcons=(oMaster.getAttribute("CompactMode")=="true");
	if (!browseris.safari)
	{
		oMaster._oContents=document.createElement("span");
		oMaster._oContents.style.display="none";
		oMaster._oContents.innerHTML=oMaster.innerHTML;
	}
	else
	{
		oMaster._oContents=oMaster.cloneNode(true);
		oMaster._oContents.style.display="none";
	}
	if(isMenuStructure != false)
	{
		if (oMaster._fLargeIconMode)
		{
			if (oMaster._fIsRtL)
				oMaster._wzMenuStyle="ms-MenuUILargeRtL";
			else
				oMaster._wzMenuStyle="ms-MenuUILarge";
		}
		else
		{
			if (oMaster._fIsRtL)
				oMaster._wzMenuStyle="ms-MenuUIRtL";
			else
				oMaster._wzMenuStyle="ms-MenuUI";
		}
		oMaster._wzChkMrkPath="/_layouts/images/ChkMrk.gif";
		oMaster._wzMArrPath="/_layouts/images/MArr.gif";
		oMaster._wzMArrPathRtL="/_layouts/images/MArrRtL.gif";
	}
}
function KSCP_MenuHtc_hide(e)
{
	KSCP_ClearTimeOutToHideMenu();
	var e = document.body.calttel;
//	if(e == null)
//		return;
	var oMaster=g_KSCP_menuHtc_lastMenu;
	if (oMaster !=null)
	{
	     KSCP_HideMenu(oMaster);
	}
    document.body.setAttribute("minicalendar", "0");
	g_KSCP_menuHtc_lastMenu=null;
}
function KSCP_ClearTimeOutToHideMenu()
{
	if (document.body.getAttribute("HideMenuTimeOut") !=null)
	{
		 KSCP_ClearTimeOut("HideMenuTimeOut");
	}
}
function KSCP_SetTimeOutToHideMenu()
{
	ClearTimeOut("HideMenuTimeOut");
	document.body.setAttribute("HideMenuTimeOut", window.setTimeout(KSCP_MenuHtc_hide, 1500));
}
var KSCP_kfnDisableEvent=new Function("return false");
var g_KSCP_menuHtc_lastMenu=null;
var g_KSCP_uniqueNumber= 0;
function KSCP_GetUniqueNumber()
{
	g_KSCP_uniqueNumber++;
	return "KSCP" + g_KSCP_uniqueNumber;
}
function KSCP_HideMenu(oMaster, nPhase)
{
	 KSCP_ClearTimeOutToHideMenu();
	if (nPhase==null)
		nPhase=0;
	if (nPhase==2)
	{
		if (oMaster._onDestroy !=null)
		{
			oMaster._onDestroy();
			oMaster._onDestroy=null;
		}
		return;
	}
	if (KSCP_IsOpen(oMaster))
	{
		if (oMaster._oParent !=null)
		{
			oMaster._oParent.onclick=oMaster._oParent._onclick;
			oMaster._oParent.onmouseover=oMaster._oParent._onmouseover;
			oMaster._oParent.onmouseout=oMaster._oParent._onmouseout;
			oMaster._oParent.onmousedown=oMaster._oParent._onmousedown;
		}
		KSCP_SetBodyEventHandlers(null);
		KSCP_UpdateLevel(oMaster, 0);
		var oPopup=oMaster._arrPopup[0];
		if (oPopup !=null)
		{
			var oBackFrame=document.getElementById(oPopup._backgroundFrameId);
			if (oBackFrame !=null)
				oBackFrame.parentNode.removeChild(oBackFrame);
			var res = oPopup.parentNode.removeChild(oPopup);
			oMaster._arrPopup[0]=null;
			if (nPhase==0)
			{
				if (oMaster._onDestroy !=null)
				{
					oMaster._onDestroy(); 
					oMaster._onDestroy=null;
				}
			}
		}
		g_CurrentShownElement = null;
		g_KSCP_menuHtc_lastMenu=null;
	}
}
function KSCP_IsOpen(oMaster)
{
	if (!oMaster._arrPopup)
		return false;
	var oPopup=oMaster._arrPopup[oMaster._nLevel];
	return oPopup;
}
function KSCP_SetBodyEventHandlers(h)
{
	document.body.onclick=h;
}
function KSCP_UpdateLevel(oMaster, nLevel)
{
	var oPopup;
	while (oMaster._nLevel > nLevel)
		{
		oPopup=oMaster._arrPopup[oMaster._nLevel];
		if (oPopup)
			{
			KSCP_ClearShowSubMenuEvnt(oPopup);
			var oBackFrame=document.getElementById(oPopup._backgroundFrameId);
			if (oBackFrame !=null)
				oBackFrame.parentNode.removeChild(oBackFrame);
			oPopup.parentNode.removeChild(oPopup);
			}
		oMaster._arrPopup[oMaster._nLevel]=null;
		oMaster._arrSelected[oMaster._nLevel]=null;
		oMaster._oRoot=oMaster._oRoot.parentNode;
		oMaster._nLevel--;
		}
	oPopup=oMaster._arrPopup[oMaster._nLevel];
	if (oPopup) KSCP_ClearShowSubMenuEvnt(oPopup);
}
function KSCP_ClearShowSubMenuEvnt(oPopup)
{
	KSCP_ClearTimeOut("timeoutID");
}
function KSCP_ClearTimeOut(oAttribute)
{
	var id=document.body.getAttribute(oAttribute);
	if (id !=null)
	{
		window.clearTimeout(id);
	}
	document.body.removeAttribute(oAttribute);
}
function KSCP_MenuHtc_init(oMaster)
{
	if (oMaster._initialized)
		return;
	oMaster._initialized=true;
	oMaster._wzPrefixID="mp"+KSCP_GetUniqueNumber();
	if (oMaster.id==null)
		oMaster.id=oMaster._wzPrefixID+"_id";
	oMaster._nLevel=0;
	oMaster._arrPopup=new Array();
	oMaster._arrSelected=new Array();
	if (typeof(oMaster._onDestroy)=="undefined")
		oMaster._onDestroy=null;
	oMaster._fLargeIconMode=false;
	oMaster._fCompactItemsWithoutIcons=false;
}
function KSCP_IsElementRtl(oCurrent)
{
	while (oCurrent !=null && oCurrent.tagName !=null)
	{
		var dir=oCurrent.getAttribute("dir");
		if ((dir==null || dir=="") && oCurrent.style !=null)
		{
			dir=oCurrent.style.direction;
		}
		if (dir=="rtl")
			return true;
		else if (dir=="ltr")
			return false;
		oCurrent=oCurrent.parentNode;
	}
	return false;
}
function KSCP_MenuHtcInternal_Show(oMaster, oParent, y, fFlipTop, isMenuStructure)
{
	var oPopup=oMaster._arrPopup[oMaster._nLevel];	
	var nIndex;							
	var fTopLevel;							
	var oInnerDiv;
	if (!oMaster._oContents) KSCP_PrepContents(oMaster, isMenuStructure);
	if (!oMaster._oContents || KSCP_IsOpen(oMaster)) return;
	if (!oPopup && !oMaster._oRoot)
		{
		oMaster._nLevel=0;
		oMaster._oRoot=oMaster._oContents;
		}
	fTopLevel=oMaster._nLevel==0;
	fFlipTop=fFlipTop && fTopLevel;
	if (!oPopup)
	{
		oMaster._arrPopup[oMaster._nLevel]=document.createElement("DIV");
		if(isMenuStructure == false)
		{
			oMaster._arrPopup[oMaster._nLevel].onclick = oMaster._oParent.onclick;
		}
		oPopup=oMaster._arrPopup[oMaster._nLevel];
		if(g_CurrentJumpPopup == null)
	        oPopup.onmouseout=function() {kwiz_cal_ItemMouseOut(); return false; };
    	oPopup.isMenu=true;
		oPopup.master=oMaster;
		oPopup.level=oMaster._nLevel;
		oInnerDiv=document.createElement("DIV");
		var oTable=document.createElement("table");
		var oTBody=document.createElement("tbody");
		oInnerDiv.isInner=true;
		oPopup.style.position="absolute";
		oInnerDiv.style.overflow="visible";
		oTable.appendChild(oTBody);
		oInnerDiv.appendChild(oTable);
		oPopup.appendChild(oInnerDiv);
		if (oMaster._fIsRtL)
			oPopup.setAttribute("dir", "rtl");
		else
			oPopup.setAttribute("dir", "ltr");
		document.body.appendChild(oPopup);
		if(isMenuStructure != false)
		{
			KSCP_FixUpMenuStructure(oMaster);
		}
		var id=0;
		var childNodeLength=oMaster._oRoot.childNodes.length;
		for (nIndex=0; nIndex < childNodeLength; nIndex++)
		{
			var oNode=oMaster._oRoot.childNodes[nIndex];
			if (oNode.nodeType !=1)
				continue;
			if (!KSCP_FIsIType(oNode, "label"))
			{
				var oItem=KSCP_CreateMenuItem(oMaster, oNode, KSCP_MakeID(oMaster, oMaster._nLevel, id), "", isMenuStructure);
				if (oItem) oTBody.appendChild(oItem);
				id++;
			}
		}
		if(isMenuStructure != false)
		{
			oPopup.className="ms-MenuUIPopupBody";
			oTable.className=oMaster._wzMenuStyle;
		}
		else
		{
			oTable.className="ms_cal_tooltipmaintable";
		}
		oTable.cellSpacing=0;
		oTable.cellPadding=0;
		if(isMenuStructure != false)
		{
			oTable.style.width = "230px";
		}
		oPopup.oncontextmenu=KSCP_kfnDisableEvent;
		oPopup.ondragstart=KSCP_kfnDisableEvent;
		oPopup.onselectstart=KSCP_kfnDisableEvent;
		if (oParent._onmouseover==null)
			oParent._onmouseover=oParent.onmouseover;
		if (oParent._onmouseout==null)
			oParent._onmouseout=oParent.onmouseout;
		if (oParent._onmousedown==null)
			oParent._onmousedown=oParent.onmousedown;
		if (oParent._onclick==null)
			oParent._onclick=oParent.onclick;
		if (fTopLevel)
		{
			var wzOnUnload=oMaster.getAttribute("onunloadtext");
			if (wzOnUnload) oPopup.onunload=new Function(wzOnUnload);
		}
	}
	else
	{
		var oOld=oMaster._arrSelected[oMaster._nLevel];
		if (oOld) UnselectItem(oOld);
	}
	oMaster._arrSelected[oMaster._nLevel]=null;
	var oBackFrame;
	if (browseris.ie)
	{
		var originalScrollLeft=document.body.scrollLeft;
		oBackFrame=document.createElement("iframe");
		KSCP_AssureId(oBackFrame);
		oBackFrame.src="/_layouts/blank.htm";
		oBackFrame.style.position="absolute";
		oBackFrame.style.display="none";
		oBackFrame.scrolling="no";
		oBackFrame.frameBorder="0";
		document.body.appendChild(oBackFrame);
		oPopup.style.zIndex=103;
		oPopup._backgroundFrameId=oBackFrame.id;
		if (originalScrollLeft !=document.body.scrollLeft)
		{
			document.body.scrollLeft=originalScrollLeft;
		}
	}
	KSCP_SetMenuPosition(oMaster, oParent, oPopup, oInnerDiv, fFlipTop, fTopLevel, isMenuStructure);
	if (browseris.ie)
	{
		KSCP_SetBackFrameSize(null, oPopup);
		oPopup.onresize=new Function("KSCP_SetBackFrameSize(event, null);");
		oBackFrame.style.display="block";
		oBackFrame.style.zIndex=101;
	}
}
function KSCP_SetBackFrameSize(e, oPopup)
{
	if (oPopup==null)
		oPopup=GetEventSrcElement(e);
	var nRealWidth=oPopup.scrollWidth+oPopup.offsetWidth - oPopup.clientWidth;
	var nRealHeight=oPopup.scrollHeight+oPopup.offsetHeight - oPopup.clientHeight;
	var oBackFrame=document.getElementById(oPopup._backgroundFrameId);
	oBackFrame.style.left=oPopup.offsetLeft+"px";
	oBackFrame.style.top=oPopup.offsetTop+"px";
	oBackFrame.style.width=nRealWidth+"px";
	oBackFrame.style.height=nRealHeight+"px";
}
function KSCP_MergeAttributes(oTarget, oSource)
{
	if (browseris.nav || oTarget.KSCP_MergeAttributes==null)
	{
		var oAttributes=oSource.attributes;
		for (var i=0; i < oAttributes.length; i++)
		{
			var oAttrib=oAttributes[i];
			if (oAttrib !=null &&
				oAttrib.specified &&
				oAttrib.nodeName !="id" &&
				oAttrib.nodeName !="ID" &&
				oAttrib.nodeName !="name")
			{
				oTarget.setAttribute(oAttrib.nodeName, oAttrib.nodeValue);
			}
		}
		if (oSource.getAttribute("type") !=null)
			oTarget.setAttribute("type", oSource.getAttribute("type"));
		if (oSource.submenuRoot !=null)
			oTarget.submenuRoot=oSource.submenuRoot;
	}
	else
	{
		oTarget.KSCP_MergeAttributes(oSource);
	}
}
function KSCP_CreateMenuItem(oMaster, oNode, wzID, wzHtml, isMenuStructure)
{
	if (KSCP_FIsIType(oNode, "label")) return;
	var oRow=document.createElement("tr");
	KSCP_MergeAttributes(oRow, oNode);
	oRow.setAttribute("onMenuClick", oNode.getAttribute("onMenuClick"));
	if (KSCP_FIsIType(oNode, "separator"))
	{
		CreateMenuSeparator(oMaster, oRow);
		return oRow;
	}
	if (!KSCP_GetIType(oNode)) KSCP_SetIType(oNode, "option");
	var oFmtTableRow=document.createElement("tr");
	var oFmtTableCell=document.createElement("td");
	var oFmtTable=document.createElement("table");
	var oFmtTableBody=document.createElement("tbody");
	oFmtTableRow.appendChild(oFmtTableCell);
	oFmtTableCell.appendChild(oFmtTable);
	oFmtTable.appendChild(oFmtTableBody);
	oFmtTableBody.appendChild(oRow);
	if(isMenuStructure != false)
	{
		if (oMaster._fCompactItemsWithoutIcons && !oNode.getAttribute("iconSrc"))
			oFmtTableCell.className="ms-MenuUIItemTableCellCompact";
		else
			oFmtTableCell.className="ms-MenuUIItemTableCell";
		oFmtTable.className="ms-MenuUIItemTable";
	}
	oFmtTable.width="100%";
	oFmtTable.cellSpacing=0;
	oFmtTable.cellPadding=0;
	if (KSCP_FIsIType(oNode, "submenu"))
		CreateSubmenu(oMaster, oRow, oNode, wzID);
	else if (KSCP_FIsIType(oNode, "option"))
		KSCP_CreateMenuOption(oMaster, oRow, oNode, wzID, wzHtml, isMenuStructure);
	if (oRow.disabled ||
		oRow.getAttribute("enabled")=="false")
	{
		oRow.disabled=false;
		oRow.className="ms-MenuUIDisabled";
		oRow.disabled=false;
		for (var nIndex=0; nIndex < oRow.childNodes.length; nIndex++)
		{
			if (oRow.childNodes[nIndex].nodeType !=1)
				continue;
			oRow.childNodes[nIndex].disabled=true;
			oFmtTableCell.className+=" ms-MenuUIItemTableCellDisabled";
		}
		oRow.optionDisabled=true;
	}
	KSCP_MergeAttributes(oFmtTableRow, oRow);
	if (oRow.optionDisabled !=null)
	{
		oFmtTableRow.optionDisabled=oRow.optionDisabled;
	}
	oFmtTableRow.id=wzID;
	KSCP_SetIType(oFmtTableRow, KSCP_GetIType(oRow));
	return oFmtTableRow;
}
function KSCP_SetIType(oItem, wzType)
{
	if (oItem) oItem.setAttribute("type", wzType);
}

function KSCP_EvalAttributeValue(oNode, sAttribute1, sAttribute2)
{
	var result=oNode.getAttribute(sAttribute2);
	if (result !=null &&
		result.toLowerCase().indexOf("javascript:")==0)
	{
		result=eval(result.substring(11));
		if (result !=null && result !="")
			return result;
	}
	var result=oNode.getAttribute(sAttribute1);
	if (result==null)
		return "";
	return result;
}

function KSCP_HandleDocumentBodyClick(e)
{
	if (g_KSCP_menuHtc_lastMenu !=null)
	{
		var oMaster=g_KSCP_menuHtc_lastMenu;
		if (oMaster !=null)
		{
			KSCP_HideMenu(oMaster);
		}
	}
}
function KSCP_SetMenuPosition(oMaster, oParent, oPopup, oInnerDiv, fFlipTop, fTopLevel, isMenuStructure)
{
	var maxWidth=window.screen.width;
	var maxHeight=window.screen.height;
	if (browseris.nav)
	{
		maxWidth=document.body.clientWidth;
		maxHeight=document.body.clientHeight;
	}
	else if (self.innerHeight)
	{
		maxWidth=self.innerWidth;
		maxHeight=self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		maxWidth=document.documentElement.clientWidth;
		maxHeight=document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		maxWidth=document.body.clientWidth;
		maxHeight=document.body.clientHeight;
	}
	var nRealWidth=oPopup.scrollWidth+oPopup.offsetWidth - oPopup.clientWidth;
	var nRealHeight=oPopup.scrollHeight+oPopup.offsetHeight - oPopup.clientHeight;
	var widthTooBig=false;
	var heightTooBig=false;
	if (nRealWidth > maxWidth - 50)
	{
		widthTooBig=true;
		nRealWidth=maxWidth - 50;
	}
	if (oMaster._fCompactItemsWithoutIcons && nRealHeight >=375)
	{
		heightTooBig=true;
		nRealHeight=375;
	}
	if (nRealHeight >=maxHeight - 50)
	{
		heightTooBig=true;
		nRealHeight=maxHeight - 50;
	}
	if (!widthTooBig && !heightTooBig)
	{
		oInnerDiv.style.overflow="visible";
	}
	else
	{
		if (browseris.ie)
		{
			if (widthTooBig)
			{
				oPopup.style.width=nRealWidth+"px";
				oInnerDiv.style.width=nRealWidth+"px";
				oInnerDiv.style.overflowX="scroll";
			}
			else
			{
				oInnerDiv.style.width=nRealWidth+"px";
				oInnerDiv.style.overflowX="visible";
			}
			if (heightTooBig)
			{
				oPopup.style.height=nRealHeight+"px";
				oInnerDiv.style.height=nRealHeight+"px";
				oInnerDiv.style.overflowY="scroll";
			}
			else
			{
				oInnerDiv.style.height=nRealHeight+"px";
				oInnerDiv.style.overflowY="visible";
			}
		}
		else
		{
			oPopup.style.height=nRealHeight+"px";
			oInnerDiv.style.height=nRealHeight+"px";
			oPopup.style.width=nRealWidth+"px";
			oInnerDiv.style.width=nRealWidth+"px";
			oInnerDiv.style.overflow="auto";
		}
	}
	nRealWidth=oPopup.scrollWidth+oPopup.offsetWidth - oPopup.clientWidth;
	nRealHeight=oPopup.scrollHeight+oPopup.offsetHeight - oPopup.clientHeight;
	var EdgeLeft=0;
	var EdgeRight=maxWidth;
	var ParentLeft=0;
	var EdgeTop=0;
	var ParentTop=0;
	var oCurrent=oParent;
	// the following code is not required as it will cause tooltip block positioning issue
	//if (browseris.safari)
	//{
	//	if (oCurrent.tagName=="TR" && oCurrent.childNodes.length > 0)
	//		oCurrent=oCurrent.childNodes[0];
	//}
	var p=KSCP_MenuHtc_GetElementPosition(oCurrent);
	ParentLeft=p.x;
	ParentTop=p.y;
	var nParentWidth;
	if (fTopLevel)
	{
		nParentWidth=p.width;
		ParentTop+=p.height;
		ParentTop -=1;
	}
	else
	{
		nParentWidth=p.width+1;
	}
	var fTryGoDefault=!fFlipTop && !document.body.getAttribute("flipped");
	var fFlippedDefault, fFlippedNonDefault;
	var xDefault, xFlipped;
	if (!oMaster._fIsRtL)
	{
		var MenuRightDefault;
		var MenuLeftFlipped;
		if (fTopLevel)
		{
			xDefault=ParentLeft;
			MenuRightDefault=ParentLeft+nRealWidth;
			MenuLeftFlipped=ParentLeft+nParentWidth - nRealWidth;
		}
		else
		{
			xDefault=ParentLeft+nParentWidth;
			MenuRightDefault=ParentLeft+nParentWidth+nRealWidth;
			MenuLeftFlipped=ParentLeft - nRealWidth;
		}
		xFlipped=MenuLeftFlipped;
		fFlippedDefault=MenuRightDefault > EdgeRight && MenuLeftFlipped > EdgeLeft;
		fFlippedNonDefault=!(MenuLeftFlipped < EdgeLeft && MenuRightDefault < EdgeRight);
	}
	else
	{
		var MenuLeftDefault;
		var MenuRightFlipped;
		if (fTopLevel)
		{
			MenuLeftDefault=ParentLeft+nParentWidth - nRealWidth;
			MenuRightFlipped=ParentLeft+nRealWidth;
			xFlipped=ParentLeft;
		}
		else
		{
			MenuLeftDefault=ParentLeft - nRealWidth;
			MenuRightFlipped=ParentLeft+nParentWidth+nRealWidth;
			xFlipped=ParentLeft+nParentWidth;
		}
		xDefault=MenuLeftDefault;
		fFlippedDefault=MenuLeftDefault < EdgeLeft && MenuRightFlipped < EdgeRight;
		fFlippedNonDefault=!(MenuRightFlipped > EdgeRight && MenuLeftDefault > EdgeLeft);
	}
	var fFlipped=fTryGoDefault ? fFlippedDefault : fFlippedNonDefault;
	var x=fFlipped ? xFlipped : xDefault;
	var xOffset;
	var yOffset;
	if (browseris.nav)
	{
		xOffset=window.pageXOffset;
		yOffset=window.pageYOffset;
	}
	else
	{
		var htmlElement=document.body.parentElement;
		if (!KSCP_IsElementRtl(document.body))
		{
			xOffset=document.body.scrollLeft;
			xOffset+=htmlElement.scrollLeft;
		}
		else
		{
			xOffset=-document.body.scrollWidth+document.body.offsetWidth+document.body.scrollLeft;
			xOffset+=-htmlElement.scrollWidth+htmlElement.offsetWidth+htmlElement.scrollLeft;
		}
		yOffset=document.body.scrollTop;
		yOffset+=htmlElement.scrollTop;
	}
	if (nRealWidth >=maxWidth)
	{
		x=xOffset;
	}
	else if (x - xOffset+nRealWidth >=maxWidth)
	{
		x=xOffset+maxWidth - nRealWidth;
	}
	var y;
	if (nRealHeight >=maxHeight)
	{
		y=yOffset;
	}
	else if (ParentTop+nRealHeight - yOffset >=maxHeight)
	{
		y=yOffset+maxHeight - nRealHeight;
	}
	else
	{
		y=ParentTop;
	}
	oPopup.setAttribute("flipped", fFlipTop ? fFlipped && fFlippedDefault : fFlipped);
	var posLeft=Math.max(x,xOffset);
	var posTop=Math.max(y,yOffset);
	oPopup.style.left=posLeft+"px";
	oPopup.style.top=posTop+"px";
}
function KSCP_AdjustScrollPosition(element, relativeToElement, result)
{
	var oCurrent=element;
	while (oCurrent !=null &&
		oCurrent !=relativeToElement &&
		oCurrent !=element.offsetParent &&
		oCurrent.tagName !=null &&
		oCurrent.tagName.toLowerCase() !="body" &&
		oCurrent.tagName.toLowerCase() !="html")
	{
		if (oCurrent.scrollWidth > oCurrent.clientWidth &&
			oCurrent.offsetWidth >=oCurrent.clientWidth &&
			oCurrent.clientWidth !=0)
		{
			if (!IsElementRtl(oCurrent))
			{
				if (oCurrent.scrollLeft > 0)
					result.x -=oCurrent.scrollLeft;
			}
			else
			{
				result.x+=(oCurrent.scrollWidth - oCurrent.offsetWidth - oCurrent.scrollLeft);
			}
		}
		if (oCurrent.scrollTop > 0)
			result.y -=oCurrent.scrollTop;
		oCurrent=oCurrent.parentNode;
	}
}
function KSCP_MenuHtc_GetElementPosition(element, relativeToElement)
{
	var result=new Object();
	result.x=0;
	result.y=0;
	result.width=0;
	result.height=0;
	if (element.offsetParent) {
		var parent=element;
		while (parent !=null &&
			parent !=relativeToElement)
		{
			result.x+=parent.offsetLeft;
			result.y+=parent.offsetTop;
			KSCP_AdjustScrollPosition(parent, relativeToElement, result);
			var parentTagName=parent.tagName.toLowerCase();
			if (parentTagName !="table" &&
				parentTagName !="body" &&
				parentTagName !="html" &&
				parentTagName !="div" &&
				parent.clientTop &&
				parent.clientLeft) {
				result.x+=parent.clientLeft;
				result.y+=parent.clientTop;
			}
			if (browseris.ie && parentTagName=="td")
			{
				if (parent.runtimeStyle.borderTopStyle !="none" ||
				    parent.currentStyle.borderTopStyle !="none")
				{
					var shift;
					if (parent.runtimeStyle.borderTopWidth !="")
					{
						shift=parseInt(parent.runtimeStyle.borderTopWidth);
					}
					else
					{
						shift=parseInt(parent.currentStyle.borderTopWidth);
					}
					if (!isNaN(shift))
					{
						result.y+=shift;
					}
				}
				if (parent.runtimeStyle.borderLeftStyle !="none" ||
				    parent.currentStyle.borderLeftStyle !="none")
				{
					var shift;
					if (parent.runtimeStyle.borderLeftWidth !="")
					{
						shift=parseInt(parent.runtimeStyle.borderLeftWidth);
					}
					else
					{
						shift=parseInt(parent.currentStyle.borderLeftWidth);
					}
					if (!isNaN(shift))
					{
						result.x+=shift;
					}
				}
			}
			parent=parent.offsetParent;
		}
	}
	else if (element.left && element.top) {
		result.x=element.left;
		result.y=element.top;
	}
	else {
		if (element.x) {
			result.x=element.x;
		}
		if (element.y) {
			result.y=element.y;
		}
	}
	if (element.offsetWidth && element.offsetHeight) {
		result.width=element.offsetWidth;
		result.height=element.offsetHeight;
	}
	else if (element.style && element.style.pixelWidth && element.style.pixelHeight) {
		result.width=element.style.pixelWidth;
		result.height=element.style.pixelHeight;
	}
	return result;
}

var g_CurrentTooltipPopup = null;
var g_CurrentShownElement = null
function KSCP_CreateTooltip(elm, tootltip, dir, sWPQ)
{
    
	if(g_CurrentShownElement == elm)
		return;
    if(g_CurrentTooltipTimeout == null)
        return;
	g_CurrentTooltipPopup = CMenu("calendartooltip");
	g_CurrentTooltipPopup.setAttribute("CompactMode", "true");
	KSCP_CreateTooltipItem(elm, g_CurrentTooltipPopup, tootltip, sWPQ);

	KSCP_OMenu(g_CurrentTooltipPopup, elm, null, null, -1, false);
    
	setTimeout(KSCP_ClearTimeOutToHideMenu, 100);
	setTimeout(function(){KSCP_SetBodyEventHandlers(KSCP_HandleDocumentBodyClick);}, 500);

}
function KSCP_CreateTooltipItem(elm, obj, html, sWPQ)
{
	var mo=document.createElement("SPAN");
//	elm.onclick = function() {kwiz_cal_GoToLink(elm, sWPQ);};
	AChld(obj,mo);
	mo.innerHTML = html;
}

function KSCP_GetSPSTooltip(webUrl, itemId, listId, type, fields, dir, useSpsTooltip, tooltipData, startDate, endDate, sWPQ)
{
	var e = document.body.calttel;
	if(fields.length == 0)
	{
		fields = fieldsXmlData;
	}
	if(useSpsTooltip.toLowerCase() == "true")
	{
		KSCP_RenderSPSTootlip(webUrl, itemId, listId, type, fields, dir, e, tooltipData, startDate, endDate, sWPQ);
	}
	else
	{
        KSCP_CreateTooltip(e, tooltipData, dir, sWPQ)
	}
}

function  KSCP_RenderSPSTootlip(webUrl, itemId, listId, type, fields, dir, parent, tooltipData, startDate, endDate, sWPQ)
{
	parent.isasync = true;
	
	Parent = parent;
	TooltipData = tooltipData;
	Dir = dir;
	WPQ = sWPQ;
	Url = webUrl + "/_layouts/kwizcom_kscp/tooltippopup.aspx?type=" + type + "&listid=" + listId + "&itemid=" + itemId + "&startdate=" + startDate + "&enddate=" + endDate + "&dir=" + dir + "&wpq=" + sWPQ;
	Data = fields;
	HttpRequest = null;
	LastReadyStatus = -1;
	KSCP_SendHttpRequest(Url, Data);
	function KSCP_CreateXMLHttpRequestObject()
	{
		try
		{
			var httpRequest = null;
			if( window.XMLHttpRequest ) // // Mozilla, Safari,...
			{
				var httpRequest = new XMLHttpRequest();
			}else if( window.ActiveXObject )  // IE
			{
				var MSXML_XMLHTTP_PROGIDS = new Array(
								'Microsoft.XMLHTTP',
								'MSXML2.XMLHTTP.5.0',
								'MSXML2.XMLHTTP.4.0',
								'MSXML2.XMLHTTP.3.0',
								'MSXML2.XMLHTTP'
								);
				for (var i=0; i < MSXML_XMLHTTP_PROGIDS.length; i++)
				{
					httpRequest = new ActiveXObject(MSXML_XMLHTTP_PROGIDS[i]);
					if( httpRequest != null )
					{
						break;
					}
				}
			}
			
			if(!httpRequest)
			{            
				KSCP_CreateTooltip(Parent, TooltipData, Dir, WPQ);
			}  
			return httpRequest;
		}
		catch(e)
		{
		}
	}

	function KSCP_ReadyStateChanged()
	{
		var XMLHTTPREQUEST_COMPLETE = 4;
		var XMLHTTPREQUEST_OK = 200;
		var XMLHTTPREQUEST_REDIRECT = 302;
		var XMLEXPIRATION = 288;             
		var currentState = null;        
		var httpCode = null;
	    
		try
		{
			currentState = HttpRequest.readyState;           
		}
		catch(e)
		{
			//Handle exception here             
		}
	                
		try
		{        
			if ((currentState == 0 || currentState == XMLHTTPREQUEST_COMPLETE) && LastReadyStatus != XMLHTTPREQUEST_COMPLETE) 
			{                        
				try
				{
					httpCode = HttpRequest.status;                
				}
				catch(e)
				{                
					httpCode = 377;                
				}
	                      
				LastReadyStatus = currentState;    
	            
				if (httpCode == XMLHTTPREQUEST_OK)
				{   
					var res = HttpRequest.responseText;
					var ind1 = res.indexOf("_Panel");
					if(ind1 < 0)
					{
					    KSCP_CreateTooltip(Parent, TooltipData, Dir, WPQ);
						return;
					}
					var ind1 = res.indexOf(">", ind1);
					var ind2 = res.lastIndexOf("</div>");
 					Parent.titlep = res.substring(ind1+1, ind2);
					//Parent.isbody = false;
					KSCP_CreateTooltip(Parent, Parent.titlep, Dir, WPQ);
			    }            
				else if (currentState != 0)
				{   
 					Parent.titlep = TooltipData;
			        KSCP_CreateTooltip(Parent, Parent.titlep, dir, WPQ)
				}
			}
			else
			{
				LastReadyStatus = currentState;   
			}        
		}
		catch(e)
		{        
	        KSCP_CreateTooltip(Parent, TooltipData, dir, WPQ)
		}
	}

	function KSCP_SendHttpRequest(url, data)
	{   
		try
		{		   				
			HttpRequest = KSCP_CreateXMLHttpRequestObject();
			HttpRequest.open("POST", url, true);
			HttpRequest.onreadystatechange = KSCP_ReadyStateChanged;
			HttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			HttpRequest.send(data);
		}
		catch(e)   
		{
	        KSCP_CreateTooltip(Parent, TooltipData, dir, WPQ)
		}
	}
}
function kwiz_cal_ShowTooltip(sWPQ)
{
	var e = document.body.calttel;
//    if(e.getAttribute("bclassname") != null)
// 	    if(e.className != (e.getAttribute("bclassname") + " " + e.getAttribute("bclassname") + "sel"))
//		    return;
     if(e.getAttribute("selclassname") != null)
 	    if(e.className != e.getAttribute("selclassname"))
		    return;
	if((e.popup != null) && (e.popup.isOpen == true))
		return;
	kwiz_cal_LocateToottip(e, "", sWPQ);
}

function kwiz_cal_LocateToottip(e, dir, sWPQ)
{
	try
	{
	    var attTitlep = e.getAttribute("titlep");
	    if(attTitlep != null)
	    {
            var data = attTitlep.split("TLTPDLM");
            // this value is not reliable, which could be "0" in FF
	        //if(document.body.getAttribute("minicalendar") == "1")
	        //    return;
	        
	        // skip tooltip display on popup table in minicalendar. inline table is in <div> "kwiz_DetailedTable" + sWPQ
	        if(e.parentNode.parentNode.parentNode.id == "" && document.getElementById("ms-cal-viewstyle" + sWPQ).value == "Mini_Calendar")
	            return;
	                        
		    if(data.length > 1)
		    {
			    eval(data[1]);
		    }
		    else
		    {
			    KSCP_CreateTooltip(e, data[0], dir, sWPQ)
		    }
		}
		else
		{
            if(e.childNodes.length == 0)
                    return;
                    
            var tooltip = null;
		    if (browseris.ie)
		    {
                if(e.childNodes[0].id != "tooltip")
                    return;
                tooltip = e.childNodes[0].innerHTML;
            } 
            else 
            {
                // FF/Chrome/Safari
                if(e.childNodes[1].id != "tooltip")
                    return;
                tooltip = e.childNodes[1].innerHTML;
            }
            
            document.body.setAttribute("minicalendar", "1");
            KSCP_CreateTooltip(e, tooltip, "", sWPQ);
		}
	}
	catch(e)
	{
	}
}

