//-- Generic AJAX Functions for requesting Data
var pag;

function InitUpdater (dataPage, dataContainer, errorContainer, _method, _parameters, _asynch, _evalJS, _evalScripts, _location, _pageCount)
{										 
    var ajaxUpdater = new Ajax.Updater
    (
        {
            success		: dataContainer,
            failure		: errorContainer //comment this out to provide more user friendly messages
        },
        dataPage, 
        {
            method		: _method, 
            parameters	: _parameters, 
            asynchronous: _asynch,
            evalJS		: _evalJS,
            evalScripts	: _evalScripts,
            insertion	: _location /*,
            onFailure	: userFriendlyErrors */
         }
    );
    
    //if pagination required this value will be higher than 0
    if(_pageCount > 0)
    {					  
        Paginate(dataPage, dataContainer, errorContainer, _method, _asynch, _evalJS, _evalScripts, _location, _pageCount);
    }
}

function userFriendlyErrors(error)   
{   
    //write the user friendly error to the user
    $(dataError).innerHTML = error.responseText;
}   
     
function Paginate(dataPage, dataContainer, errorContainer, _method, _asynch, _evalJS, _evalScripts, _location, _pageCount)
{														
    //create new instance of the yahoo paginator object
    pag = new YAHOO.widget.Paginator
    (
        {   
             rowsPerPage		   : 1,   
             totalRecords		   : 1,   
             containers			   : [ "divPager" ],
             nextPageLinkLabel	   : '&gt;',
             previousPageLinkLabel : '&lt;',
             previousPageLinkClass : '',
             pageLinkClass		   : '',   
             nextPageLinkClass	   : '',
             pageLinks			   : _pageCount,
             template			   : "{PreviousPageLink} {PageLinks} {NextPageLink}"   
        }
    );  
    
    pag.render();   

    MyApp = 
    {   
         handlePagination : function (newState) 
         {   
             //make a new updater request with the parameters set for pagination
             InitUpdater (dataPage, dataContainer, errorContainer, _method, 'p=' + newState.page, _asynch, _evalJS, _evalScripts, _location);    

             // Update the Paginator's state   
             pag.setState(newState);   
        }   
    };   
   
    pag.subscribe('changeRequest',MyApp.handlePagination);   
}          
          
function setPager (rowsPerPage, totalCount) 
{												 
    pag.setRowsPerPage(rowsPerPage, true);
    pag.setTotalRecords(totalCount, true);
}

// ----- other commonly used functions
function SelectAll (theElement, checkit)
{
 var theForm = theElement.form;
 for (var i = 0; i<theForm.elements.length; i++) 
  {
	if (theForm[i].type == 'checkbox')
		{theForm[i].checked = checkit;}
  }
}

function Select_All (checkit)
{
	var theForm = document.forms[0];
	for (var i = 0; i<theForm.elements.length; i++) 
	{
		if (theForm[i].type == 'checkbox' && !theForm[i].disabled)
			{theForm[i].checked = checkit;}
	}
}

function setCheckedValue (radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

// This routine is called by the onLoad event - Handles the init of the display
function OnLoad()
{
	// Change the "Loading..." text
	ShowLoading (true, 'Rendering...');
	// Make sure the "Loading..." display is hidden (so we can see the data)
	// Use .setTimeout() to deal with bug when page is refreshed (and "Loading..." doesn't hide)
	window.setTimeout ('ShowLoading (false);',100);
}

//sets provided html control with the provided value
function SetField (control, value)
{ 
    $(control).value=value;
}

//clears html controls
function ClearField (control)
{   
    SetField (control, '');
}

// Shows or Hides the "Loading..." message
function ShowLoading(blnShow, strText)
{
	var divLoadingText	= document.getElementById ('divLoadingText');
	var divData			= document.getElementById ('divData');
	var divLoading		= document.getElementById ('divLoading');

	if (!divLoadingText)	return;
	if (!divData)			return;
	if (!divLoading)		return;

	if (blnShow)
	{
		if (strText)	divLoadingText.innerHTML = strText;
		divData.style.display	 = 'none';
		divLoading.style.display = '';
	}
	else
	{
		divLoading.style.display = 'none';
		divData.style.display	 = '';
		divLoadingText.innerHTML = 'Loading...';
	}
}

function textAreasInit()
{  
	var objs = document.getElementsByTagName("textarea");
	var oi = 0; // object index  
	var thisObj;  
	for (oi=0;oi<objs.length;oi++) 
	{   
		thisObj = objs[oi];   // MaxLength is case sensitve   
		if (thisObj.getAttribute('MaxLength'))
		{    
			thisObj.onkeyup = forceMaxLength;   
		}   
		///thisObj.onchange = saveEntryValue;  
	} 
} 

function forceMaxLength()
{  
	var maxLength = parseInt(this.getAttribute('MaxLength'));  
	if(this.value.length > maxLength)
	{   
		this.value = this.value.substring(0,maxLength);  
	} 
}

// addEvent - cross-browser event handling for IE5+,  NS6 and Mozilla 
function addEvent(elm, evType, fn, useCapture) 
{   
	if (elm.addEventListener)
	{  
		elm.addEventListener (evType, fn, useCapture);  
		return true;   
	} 
	else if (elm.attachEvent)
	{  
		var r = elm.attachEvent("on"+evType, fn);  
		return r;   
	} 
	else 
	{  
	//alert("Handler could not be removed");   
	} 
}

function ShowConfirmMsg(objId, showDuration){
	var obj = $(objId);
	if (obj) 
	{
		obj.style.visibility = "visible";
		if (obj.style.display == "none") 
		{
			obj.style.display = "";
		}
		window.setTimeout(function () { $(objId).style.visibility = "hidden"; }, showDuration);
	}
}

// checkForEnterKey - this method checks to see if the enter key was pressed
// and returns true if it was the last key pressed
function checkForEnterKey (e) 
{	
	var key;	
	
	if(window.event)
		key = window.event.keyCode;     //IE
	else
		key = e.which;
		
	if (key == 13)
		return true;
	else
		return false;                      
}

// Replace all occurrances of a string within a string
function ReplaceAll( inText, inFindStr, inReplStr, inCaseSensitive ) 
{
   //	inText is the text in which to do the search;
   //	inFindStr is the string to find;
   //	inReplStr is the string to substitute into inText in place of inFindStr; and
   //	inCaseSensitive is a boolean value (defaults to false).
   
   var searchFrom = 0;
   var offset = 0;
   var outText = "";
   var searchText = "";
   if ( inCaseSensitive == null ) {
      inCaseSensitive = false;
   }
   if ( inCaseSensitive ) {
      searchText = inText.toLowerCase();
      inFindStr = inFindStr.toLowerCase();
   } else {
      searchText = inText;
   }
   offset = searchText.indexOf( inFindStr, searchFrom );
   while ( offset != -1 ) {
      outText += inText.substring( searchFrom, offset );
      outText += inReplStr;
      searchFrom = offset + inFindStr.length;
      offset = searchText.indexOf( inFindStr, searchFrom );
   }
   outText += inText.substring( searchFrom, inText.length );
   
   return ( outText );
}

// These are place holders for silent error catching
// to be removed when omm player is updated.
function _hbSet(){}
function _hbSend(){}



// ----------------------------------------------- //
// THIS IS THE NEW AJAX CODE FOR COMMUNITY WIDGETS //
// ----------------------------------------------- //
var ajaxPager;
function AjaxReqInit (ajaxParams,ajaxPage){			  
    var ajaxRequest = new Ajax.Request(ajaxPage, {
        method:			'get', 
        parameters:		ajaxParams, 
        asynchronous:	true,
        evalJS:			true,
        evalScripts:	true,
        onComplete:		showResponse, 
        onFailure:		function (transport) {var val = transport.responseText;}
    });
    ajaxPager = new YAHOO.widget.Paginator({   
         rowsPerPage			: 1,   
         totalRecords			: 1,   
         containers				: [ "divAjaxPager" ],
         nextPageLinkLabel		: '&#187;',
         previousPageLinkLabel	: '&#171;',
         previousPageLinkClass	: 'pagerPrevious',
         pageLinkClass			: 'pager',
         currentPageClass		: 'pagerCurrentPage',   
         nextPageLinkClass		: 'pagerNext',
         pageReportClass		: 'pageReport',
         containerClass			: 'pagerContainer',
         pageLinks				: 4,
         template				: '<div>{CurrentPageReport}</div>' +
								  '{PreviousPageLink} {PageLinks} {NextPageLink}', 
         alwaysVisible			: false,
         pageReportValueGenerator : function (paginator) {
			var recs = paginator.getPageRecords();	
			return {
				start	: recs[0]+1,
				end		: recs[1]+1,
				total	: paginator.getTotalRecords()
			};
		},
		pageLabelBuilder : function (page, paginator) {
			if (page == paginator.getCurrentPage()) {
				return '[' + page + ']';
			} else {
				return page;
			}
		},
		pageReportTemplate		: '{start} - {end} of {total}'
     });   
          
    ajaxPager.render();
	
    var MyApp = {   
         handlePagination : function (newState) 
         {											  
             var ajaxRequest = new Ajax.Request(ajaxPage, 
             {
                method		: 'get', 
                parameters	: ajaxParams+'&p='+newState.page, 
                asynchronous: true,
                evalJS		: true,  
                evalScripts	: true,
                onComplete	: showResponse, 
                onFailure	: function (transport) {var val = transport.responseText;} //errorMedia		
             });

             // Update the Paginator's state   
             ajaxPager.setState(newState);   
        }   
    };   
   
    ajaxPager.subscribe('changeRequest',MyApp.handlePagination);   
}
function showResponse(xmlHttpRequest, responseHeader) {	
    xmlHttpRequest.responseText.evalScripts();
    $('divAjaxData').innerHTML = xmlHttpRequest.responseText;
}
function SetAjaxPager (rowsPerPage, totalCount, initialPage) {													  
	if (ajaxPager) {								
		ajaxPager.setRowsPerPage(rowsPerPage, true);
		ajaxPager.setTotalRecords(totalCount, true);

		if (initialPage && initialPage > 0) ajaxPager.setPage (initialPage, true); 
    }  
}


