//////////////////////////////////////////////////////////////////////////////////////////
//
// FotoWeb AJAX Java Scripts.
//
//////////////////////////////////////////////////////////////////////////////////////////


//
// Globals.
//

var g_quickListVersions = new Array(1000); // Used for Iptc quick list version control.


//
// Description: Creates HTTP request object.
// Arguments:   None.
// Returns:     XML HTTP Request Object, or null upon failure.
//
function fwAjax_CreateHttpRequest()
{
	var xmlHttpReq = null;
	
	if (window.XMLHttpRequest)
	{
		try
		{
			xmlHttpReq = new XMLHttpRequest();
			
			// Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML mime-type header.
			// To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not text/xml.
			//if (!g_browser.isOpera  && !g_browser.isExplorer)
			//{
			//	xmlHttpReq.overrideMimeType('text/xml');
			//}
			if (xmlHttpReq.overrideMimeType)
			{
			    xmlHttpReq.overrideMimeType('text/xml');
			}
      
		}
		catch (ex)
		{
			return(null);
		}
	}
	else if (window.ActiveXObject)
	{
		// Try Active X.
		try
		{ 
			xmlHttpReq = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (ex1)
		{
			// Try alternative approach.
			try
			{
				xmlHttpReq = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (ex2)
			{
				return(null);
			} 
		}
	}

	return(xmlHttpReq);
}




//
// Description: Evaluates the ready state for the Http request object.
// Arguments:   http_request - XML HTTP Request object.
// Returns:     Returns string 'XML', 'TEXT' or null.
//
function fwAjax_ReadyStateHandler(http_request)
{
	fwDebugPrint('fwAjax_ReadyStateHandler');
	
	if (http_request.readyState == 4 || http_request.readyState == 'complete')
	{
		if (http_request.status == 200)
		{
			if (http_request.responseXML)
			{
				return('XML');
			}
			else if(http_request.responseText)
			{
				return('TEXT');
			}
			else
			{
				fwDebugPrint('NO response from the server.');
			}
		}
		else
		{	
			fwDebugPrint('Status Error: Status is ' + http_request.status);
		}
	}
	else
	{
		fwDebugPrint('Ready State Error: Ready state is ' + http_request.readyState);
	}
	
	return(null);
}




//
// Description: Creates a dummy query string parameter to be added to the server calls.
//              This is to enforce each request to be unique so that the server does not return cached data.
// Arguments:   None.
// Returns:     A dummy query string parameter.
//
function AddDummyParam()
{
	var d = new Date();
	return('dp=' + d.getHours() + d.getMinutes() + d.getSeconds() + d.getMilliseconds());
	
	// or
	return('dp=' + Math.random());
}




//
// Description: Adds a file to FotoWeb selection list.
// Arguments:   fileId - Foxtoken of the file to add.
//              statusElementId - Id of the element to display status in.
//              listId - Id of the list to display thumbnails in.
// Returns:     None.
//
function fwAjax_AddToSelection(fileId, statusElementId, listId)
{
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_AddToSelection: Cannot create Http request.');
		return;
	}
	
	// Register the callback handler function and send the request.
	http_request.onreadystatechange = fwAjax_SelectionReadyStateHandler(http_request, statusElementId, listId);
	http_request.open('GET', '/fotoweb/cmdrequest/AddToSelection.fwx?sendXML=1&fileId=' + fileId + '&' + AddDummyParam(), true);
	http_request.send(null);
}




//
// Description: Removes a file from FotoWeb selection list.
// Arguments:   fileId - Foxtoken of the file to remove.
//              statusElementId - Id of the element to display status in.
//              listId - Id of the list to display thumbnails in.
// Returns:     None.
//
function fwAjax_RemoveFromSelection(fileId, statusElementId, listId)
{
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_RemoveFromSelection: Cannot create Http request.');
		return;
	}

	// Register the callback handler function and send the request.
	http_request.onreadystatechange = fwAjax_SelectionReadyStateHandler(http_request, statusElementId, listId);
	http_request.open('GET', '/fotoweb/cmdrequest/RemoveFromSelection.fwx?sendXML=1&fileId=' + fileId + '&' + AddDummyParam(), true);
	http_request.send(null);
}




//
// Description: Clears the FotoWeb selection list.
// Arguments:   statusElementId - Id of the element to display status in.
//              listId - Id of the list to display thumbnails in.
// Returns:     None.
//
function fwAjax_ClearSelection(statusElementId, listId)
{
	// Create request object.
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_ClearSelection: Cannot create Http request.');
		return;
	}

	// Register the callback handler function and send the request.
	http_request.onreadystatechange = fwAjax_SelectionReadyStateHandler(http_request, statusElementId, listId);
	http_request.open('GET', '/fotoweb/cmdrequest/ClearSelection.fwx?sendXML=1&' + AddDummyParam(), true);
	http_request.send(null);
}




//
// Description: Sets processing profile to the specified files.
// Arguments:   fileId - Foxtoken of the file to change processing profile of.
//              profile - Name of the profile to set for the file.
//              deliveryType - Type of delivery for the relevant operation.
//              callbackStr - A string representing the callback function call.
// Returns:     None.
//
function fwAjax_SetProcessingProfile(fileId, profile, deliveryType, callbackStr)
{
	// Create request object.
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_SetProcessingProfile: Cannot create Http request.');
		return;
	}

	// Register the callback handler function and send the request.
	http_request.onreadystatechange = fwAjax_SetProcessingProfileReadyStateHandler(http_request, callbackStr);
	http_request.open('GET', '/fotoweb/cmdrequest/SetProcessingProfile.fwx?sendXML=1&fileId=' + fileId + '&deliveryType=' + deliveryType + '&profile=' + profile + '&' + AddDummyParam(), true);
	http_request.send(null);
}




//
// Description: Handles the change of ready state for operations with FotoWeb selection list.
// Arguments:   http_request - XML HTTP Request object.
//              statusElementId - Id of the element to display status in.
//              listId - Id of the list to display thumbnails in.
// Returns:     None.
//
function fwAjax_SelectionReadyStateHandler(http_request, statusElementId, listId)
{
	return function ()
	{
		var readyState = fwAjax_ReadyStateHandler(http_request);
		if(readyState)
		{
			if(readyState == 'XML')
			{
				fwAjax_SelectionResponseHandler(http_request.responseXML, statusElementId, listId);
			}
			else if(readyState == 'TEXT')
			{
				// Update status.
				var statusElement = document.getElementById(statusElementId);
				if (statusElement)
				{
					statusElement.innerHTML =  http_request.responseText;
				}
			}
		}
	}
}




//
// Description: Handles the change of ready state for operations with FotoWeb processing profiles.
// Arguments:   http_request - XML HTTP Request object.
//              callbackStr - A string representing the callback function call.
// Returns:     None.
//
function fwAjax_SetProcessingProfileReadyStateHandler(http_request, callbackStr)
{
	return function ()
	{
		var readyState = fwAjax_ReadyStateHandler(http_request);
		if(readyState)
		{
			if(readyState == 'XML')
			{
				fwAjax_SetProcessingProfileResponseHandler(http_request.responseXML, callbackStr);
			}
			else if(readyState == 'TEXT')
			{
			    if(callbackStr != null && callbackStr != '')
			    {
				    eval(callbackStr);
				}
			}
		}
	}
}




//
// Description: Handles the XMl response from the server.
// Arguments:   xmlData - XML data received from the server
//              statusElementId - Id of the element to display status in.
//              listId - Id of the list to display thumbnails in.
// Returns:     None.
//
function fwAjax_SelectionResponseHandler(xmlData, statusElementId, listId)
{
	// Get the root node and the list count.
	var rootNode = xmlData.getElementsByTagName('SelectionList')[0];
	if (!rootNode)
	{
		fwDebugPrint('fwAjax_SelectionResponseHandler: No root node.');
		return;
	}
	
	var listCount = parseInt(rootNode.getAttribute('listCount'));
	
	// Update status.
	var statusElement = document.getElementById(statusElementId);
	if (statusElement)
	{
		statusElement.innerHTML = listCount;
	}
	else
	{
		fwDebugPrint('fwAjax_SelectionResponseHandler: Cannot find status element on the page.');
	}
	
	var clearSelectionLink = document.getElementById('clearSel');
	if (clearSelectionLink)
	{
		if (listCount > 0)
		{
			clearSelectionLink.style.visibility = 'visible';
		}
		else
		{
			clearSelectionLink.style.visibility = 'hidden';
		}
	}
	else
	{
		fwDebugPrint('fwAjax_SelectionResponseHandler: Cannot find clear selection link on the page.');
	}
	
	
	// Clear current selection list.
	var selectionList = document.getElementById(listId);
	if (!selectionList)
	{
		fwDebugPrint('fwAjax_SelectionResponseHandler: No selection list found (' + listId + ').');
		return;
	}
	
	selectionList.innerHTML = '';
	
	// Get current selection items.
	var selectedItems = rootNode.getElementsByTagName('Item');
	
	
	var index = 0;
	while(selectedItems[index])
	{
		var pvLink = selectedItems[index].getAttribute('pvLink');
		var imgWidth = selectedItems[index].getAttribute('width');
		var imgHeight = selectedItems[index].getAttribute('height');
		
		var icon = document.createElement('img');
		if (icon)
		{
			icon.className = 'fwSelectedImage';
			icon.src = pvLink;
			icon.style.width = imgWidth + 'px';
			icon.style.height = imgHeight + 'px';
			icon.style.border = 0 + 'px';
			
			selectionList.appendChild(icon);
		}

		index++;
	}
}




//
// Description: Handles the XMl response from the server.
// Arguments:   xmlData - XML data received from the server
//              callbackStr - A string representing the callback function call.
// Returns:     None.
//
function fwAjax_SetProcessingProfileResponseHandler(xmlData, callbackStr)
{
	// Get the root node and the list count.
	var rootNode = xmlData.getElementsByTagName('Results')[0];
	if (!rootNode)
	{
		fwDebugPrint('fwAjax_SetProcessingProfileResponseHandler: No root node.');
		return;
	}
	
	var resultValue = rootNode.getAttribute('value') == "Yes" ? true : false;
	
    if(callbackStr != null && callbackStr != '')
    {
	    eval(callbackStr);
	}
}




//
// Description: Retrieves the quick list from the server.
// Arguments:   archiveId - Id of the relevant archive.
//              iptcField - Id of the Iptc field to get.
//              listControlId - The list control in the Html to populate.
//              adjustDimesions - Flag to update dimensions of the list control after update.
//              showAliasOnly - Flag to only show aliases in the list.
// Returns:     None.
//
function fwAjax_GetQuickList(archiveId, iptcField, listControlId, adjustDimesions, showAliasOnly)
{
	fwDebugPrint('fwAjax_GetQuickList(' + archiveId + ', ' + iptcField + ', ' + listControlId + ')');
	
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_GetQuickList: Cannot create Http request.');
		return;
	}
	
	var url = '/fotoweb/cmdrequest/GetQuickList.fwx?archiveId=' + archiveId + '&iptcField=' + iptcField + '&' + AddDummyParam();
	
	if(g_quickListVersions)
	{
		url += '&version=';
		
		if (g_quickListVersions[iptcField])
		{
			url += g_quickListVersions[iptcField];
		}
		else
		{
			url += '00000000 000000';
		}
	}
	
	// Register the callback handler function and send the request.
	http_request.onreadystatechange = fwAjax_GetQuickListReadyStateHandler(http_request, listControlId, adjustDimesions, showAliasOnly);
	http_request.open('GET', url, true);
	http_request.send(null);
	
	fwDebugPrint('fwAjax_GetQuickList: Request submitted.');
}




//
// Description: Handles the change of ready state for operations with quick list.
// Arguments:   http_request - XML HTTP Request object.
//              listControlId - Id of the list control to populate.
//              adjustDimesions - Flag to update dimensions of the list control after update.
//              showAliasOnly - Flag to only show aliases in the list.
// Returns:     None.
//
function fwAjax_GetQuickListReadyStateHandler(http_request, listControlId, adjustDimesions, showAliasOnly)
{
	fwDebugPrint('fwAjax_GetQuickListReadyStateHandler: Response received from server.');
	
	return function ()
	{
		var readyState = fwAjax_ReadyStateHandler(http_request);
		if(readyState)
		{
			if(readyState == 'XML')
			{
				fwDebugPrint('fwAjax_GetQuickListReadyStateHandler: XML response received from the server');
				fwAjax_GetQuickListResponseHandler(http_request.responseXML, listControlId, adjustDimesions, showAliasOnly);
			}
			else if(readyState == 'TEXT')
			{
				fwDebugPrint('fwAjax_GetQuickListReadyStateHandler: Text response from the server (' + http_request.responseText + ')');
			}
		}
	}
}




//
// Description: Handles the XMl response from the server.
// Arguments:   xmlData - XML data received from the server
//              listControlId - Id of the list control to populate.
//              adjustDimesions - Flag to adjust list box dimensions after update.
//              showAliasOnly - Flag to only show aliases in the list.
// Returns:     None.
//
function fwAjax_GetQuickListResponseHandler(xmlData, listControlId, adjustDimesions, showAliasOnly)
{
	// Get the root node and the list count.
	var rootNode = xmlData.getElementsByTagName('QuickList')[0];
	if (!rootNode)
	{
		fwDebugPrint('fwAjax_GetQuickListResponseHandler: No root node.');
		return;
	}
	
	var iptcField = parseInt(rootNode.getAttribute('iptcField') + '');
	var listCount = rootNode.getAttribute('listCount');
	var listVersion = rootNode.getAttribute('listVersion') + '';
	
	if(g_quickListVersions)
	{
		g_quickListVersions[iptcField] = listVersion;
	}
	
	fwDebugPrint('fwAjax_GetQuickListResponseHandler: Items received: ' + listCount + '.');
	
	// Fill list control with the quick list.
	var qListCtrl = document.getElementById(listControlId);
	if (!qListCtrl)
	{
		fwDebugPrint('fwAjax_GetQuickListResponseHandler: Cannot find list control (' + listControlId + ').');
		return;
	}
	
	// Clear the current contents of the list control.
	while (qListCtrl.length > 0)
	{
		qListCtrl.remove(qListCtrl.length - 1);
	}
	
	// Get current selection items.
	var selectedItems = rootNode.getElementsByTagName('Item');
	
	var index = 0;
	while(selectedItems[index])
	{
		var itemName = selectedItems[index].getAttribute('name');
		var itemText = itemName;
		var itemValue = itemName;
		
		if(showAliasOnly)
		{
			var pos = itemName.indexOf('=');
			if(pos != -1)
			{
				itemValue = itemName.substring(0, pos);
				itemText = itemName.substring(pos + 1, itemName.length);
			}
		}

		var newOption = document.createElement('option');
		if (newOption)
		{
			newOption.text = itemText;
			newOption.value = itemValue;

			try
			{
				qListCtrl.add(newOption, null); // May not work in IE.
			}
			catch(ex)
			{
				qListCtrl.add(newOption); // Alternative upon failure.
			}
		}
		else
		{
			fwDebugPrint('fwAjax_GetQuickListResponseHandler: Cannot create new option.');
		}
		
		index++;
	}
	
	if (adjustDimesions)
	{
		if (qListCtrl.length < 3)
		{
			qListCtrl.size = 3;
		}
		else if (qListCtrl.length > 10)
		{
			qListCtrl.size = 10;
		}
		else
		{
			qListCtrl.size = qListCtrl.length;
		}
	}
}


//
// Description: Updates the quick list on the server.
// Arguments:   archiveId - Id of the relevant archive.
//              iptcField - Id of the Iptc field to update.
//              queryString - Query string with add/remove parameters.
// Returns:     None.
//
function fwAjax_UpdateQuickList(archiveId, iptcField, queryString)
{
	fwDebugPrint('fwAjax_UpdateQuickList(' + archiveId + ', ' + iptcField + ', ' + queryString + ')');
	
	var http_request = fwAjax_CreateHttpRequest();
	if (!http_request)
	{
		fwDebugPrint('fwAjax_UpdateQuickList: Cannot create Http request.');
		return;
	}
	
	// We will be making a post request
	var url = '/fotoweb/cmdrequest/UpdateQuickList.fwx';
	var params = '?archiveId=' + archiveId + '&iptcField=' + iptcField + '&' + queryString;

	http_request.onreadystatechange = fwAjax_UpdateQuickListReadyStateHandler(http_request);
	http_request.open('GET', url + params, false);
	http_request.send(null);
	
	fwDebugPrint('fwAjax_UpdateQuickList: Request submitted.');
}




//
// Description: Handles the change of ready state for operations with quick list.
// Arguments:   http_request - XML HTTP Request object.
// Returns:     None.
//
function fwAjax_UpdateQuickListReadyStateHandler(http_request)
{
	fwDebugPrint('fwAjax_UpdateQuickListReadyStateHandler: Response received from server.');
	
	return function ()
	{
		var readyState = fwAjax_ReadyStateHandler(http_request);
		if(readyState)
		{
			if(readyState == 'XML')
			{
				fwDebugPrint('fwAjax_UpdateQuickListReadyStateHandler: XML response received from the server');
			}
			else if(readyState == 'TEXT')
			{
				fwDebugPrint('fwAjax_UpdateQuickListReadyStateHandler: Text response from the server (' + http_request.responseText + ')');
			}
		}
	}
}


//
// Description: Handles the XMl response from the server.
// Arguments:   xmlData - XML data received from the server
// Returns:     None.
//
function fwAjax_UpdateQuickListResponseHandler(xmlData)
{
	// Get the root node and the list count.
	var rootNode = xmlData.getElementsByTagName('QuickList')[0];
	if (!rootNode)
	{
		fwDebugPrint('fwAjax_UpdateQuickListResponseHandler: No root node.');
		return;
	}
	
	var iptcField = parseInt(rootNode.getAttribute('iptcField') + '');
	var listVersion = rootNode.getAttribute('listVersion') + '';
	
	if(g_quickListVersions)
	{
		g_quickListVersions[iptcField] = listVersion;
	}
}




/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url =
{
    // public method for url encoding
    encode : function (string)
    {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string)
    {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string)
    {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++)
        {

            var c = string.charCodeAt(n);

            if (c < 128)
            {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048))
            {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else
            {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext)
    {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128)
            {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224))
            {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else
            {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}


