// Modal Window Stuff
var winModalWindow;
var manager = new Object ();
var contextRoot = null;
var yuiDateConfig = null;
var formSubmitting = false;

function log (a, b, c, d, e)
{
    if ( window.console && window.console.log ) 
    {
      // console is available
      window.console.log ("utils.js Log", a, b, c, d);
    }
}

function submitForm(tag)
{
    log("submitForm", tag);
    var htmlElement = $(tag);
    var aForm = htmlElement.closest('form');
    formSubmitting = true;
    aForm.submit();		
}


function clickButtonGeneric(formName, buttonID)
{
    log("clickButtonGeneric", formName, buttonID);
    
    var $buttonSelectInput = $("#" + formName + "buttonSelect");
    
    $buttonSelectInput.val (buttonID);
    formSubmitting = true;
}


function IgnoreEvents(e)
{
  return false;
}

function HandleFocus()
{
    if (winModalWindow)
    {
        if (!winModalWindow.closed)
        {
          winModalWindow.focus()
        }
        else
        {
          //window.top.releaseEvents (Event.CLICK|Event.FOCUS)
          window.top.onclick = ""
          window.top.onfocus=""
        }
    }

    return false
}

function ShowModalWindow(page, callback, width, height)
{
    //window.top.captureEvents (Event.CLICK|Event.FOCUS)
    window.top.onclick=IgnoreEvents
    window.top.onfocus=HandleFocus
    winModalWindow = window.open (page,"_blank", "dependent=yes,width=" + width + ",height=" + height + ",location=no,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no")
    //winModalWindow.modalParent = this;
    manager.callBack = callback;
    winModalWindow.focus()
}

function devNull () {}



function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  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");
  }
} 

var allYUICalendars = {};
daySuffix = ["DAY", "Date"];
monthSuffix = ["MONTH", "Month"];
yearSuffix = ["YEAR", "Year"];


function initYUICalendar (name, suffixIndex)
{
    if (!suffixIndex)
    {
        suffixIndex = 0;
    }

    var theTitle = "Choose a date";
    
    if (yuiDateConfig)
    {
        theTitle = yuiDateConfig.PopupTitle
    }
    
    var theCalendar = new YAHOO.widget.Calendar(name, name + "CalendarContainer", {title: theTitle + ":", close:true} );

    if (yuiDateConfig)
    {
        theCalendar.cfg.setProperty("MONTHS_LONG",    yuiDateConfig.MONTHS_LONG); 
        theCalendar.cfg.setProperty("WEEKDAYS_SHORT", yuiDateConfig.WEEKDAYS_SHORT); 
    }
    
    theCalendar.render ();
    YAHOO.util.Event.addListener(name + "CalendarPicker", "click", theCalendar.show, theCalendar, true);
    theCalendar.selectEvent.subscribe(function (type,args,obj) {
            if (theCalendar.oneitInitialised)
            {
                handleYUICalendarSelect(type,args,obj, suffixIndex)
            }
        }, theCalendar, true);

    YAHOO.util.Event.addListener([name + daySuffix[suffixIndex], name + monthSuffix[suffixIndex], name + yearSuffix[suffixIndex]], "change", function () {updateYUICalendarFromFields (theCalendar, suffixIndex);});
    YAHOO.util.Event.onDOMReady (function () {
            updateYUICalendarFromFields(theCalendar);
            theCalendar.oneitInitialised = true;
        });
    allYUICalendars[name] = theCalendar;
    
    return theCalendar;
}


function handleYUICalendarSelect (type,args,obj, suffixIndex)
{
    if (!suffixIndex)
    {
        suffixIndex = 0;
    }

    var dates = args[0];
    var date = dates[0];

    $('#' + obj.id + daySuffix[suffixIndex]).val("" + date[2]);
    $('#' + obj.id + monthSuffix[suffixIndex]).val("" + date[1]);
    $('#' + obj.id + yearSuffix[suffixIndex]).val("" + date[0]);

    // Manually trigger a recalc
    var     aForm = $('#' + obj.id + daySuffix[suffixIndex]).parents('form');
    
    if (window.recalcFunctions && window.recalcFunctions[aForm.attr("id")])
    {
        recalcFunctions[aForm.attr("id")]();
    }
    
    obj.hide ();
}


function updateYUICalendarFromFields (obj, suffixIndex)
{
    if (!suffixIndex)
    {
        suffixIndex = 0;
    }

    var selDay = $('#' + obj.id + daySuffix[suffixIndex]).val();
    var selMonth = $('#' + obj.id + monthSuffix[suffixIndex]).val();
    var selYear = $('#' + obj.id + yearSuffix[suffixIndex]).val();
    updateYUICalendarFromParts (obj, parseInt(selDay), parseInt(selMonth), parseInt(selYear));
}
    
    
function updateYUICalendarFromParts (obj, day, month, year)
{
    if (! isNaN(month) && ! isNaN(day) && ! isNaN(year)) 
    {
        var date = month + "/" + day + "/" + year;

        obj.select(date);
        obj.cfg.setProperty("pagedate", month + "/" + year);
        obj.render();
    }
}


function eachInitYUIDate(index, domElement)
{
    var dateTagID = domElement.id;
    var checker = $(domElement).find ("input");

    if (checker.length > 0)
    {
        var yuiPicker = "<img id='" + dateTagID + "CalendarPicker' src='" + (contextRoot != null ? contextRoot : ".") + "/images/caloff.gif' alt='Select Date'><div class='dateCalendarContainerHolder'><div class='dateCalendarContainer' id='" + dateTagID + "CalendarContainer'></div></div>";

        $("#" + dateTagID).after (yuiPicker);
        initYUICalendar (dateTagID, 0);
    }
}


function eachInitYUIDate2(index, domElement)
{
    var dateTagID = domElement.id;
    var checker = $(domElement).find ("input");

    if (checker.length > 0)
    {
        var yuiPicker = "<img id='" + dateTagID + "CalendarPicker' src='" + (contextRoot != null ? contextRoot : ".") + "/images/caloff.gif' alt='Select Date'><div class='dateCalendarContainerHolder'><div class='dateCalendarContainer' id='" + dateTagID + "CalendarContainer'></div></div>";

        $("#" + dateTagID).after (yuiPicker);
        initYUICalendar (dateTagID, 1);
    }
}


function initORMMultiassocAutocomplete($multiLink)
{
    var     url = $multiLink.attr("data-url");
    var     varkey = $multiLink.attr("data-varkey");           
    var     aForm = $multiLink.parents('form');
    var     procID = aForm.find("input[name = 'proc.ID']").val();
    var     procStage = aForm.find("input[name = 'proc.stage']").val ();
    var     theDialog = $("#iFrameDialog");

    theDialog.html ("<iframe class='popup' width='100%' height='100%' src='" + (url + "?varKey=" + varkey + "&proc.ID=" + procID + "&proc.stage=" + procStage) + "'>");
    theDialog.dialog ({ height: 500, width: 500, modal: true });

    manager.onSuccess = function (result) {
            var  procStage   = result.stage;

            aForm.find("input[name = 'proc.stage']").val (procStage);
            $multiLink.attr ("title", result.data.title);
            $multiLink.html(result.data.desc);
            theDialog.dialog ("close");
        };
    manager.onFailure = function (data) {
            theDialog.dialog ("close");
        };
}

function eachInitORMMultiassocAutocomplete (domElement)
{
    var     $multiLink = $(domElement);
    var     $multiButton = $(domElement).parent().find("button, input[type=button]");

    $multiButton.click(function () { 
       initORMMultiassocAutocomplete($multiLink);
    });
    
    $multiLink.click (function () { 
        initORMMultiassocAutocomplete($multiLink);
        });
}


function eachInitiORMSingleAssocAutocomplete (domElement)
{
    var     jqAutocomplete = $(domElement).find(".autocomplete_text");
    var     jqActiveDesc = $(domElement).find(".autocomplete_active_desc");
    var     jqID = $(domElement).find(".autocomplete_id");
    var     theMinLength = 3;
    var     aForm = jqAutocomplete.parents('form');
    var     autosubmit = $(domElement).find(".autocomplete_autosubmit");
    var     autosubmitFlag = (autosubmit == null || autosubmit.val() == null) ? false : true;
    var     submitFields = $(domElement).attr ("data-submitfields");
    var     defaultValue = jqAutocomplete.val();
    var     errorFunction = $(domElement).attr ("error-function");
    var     bSelected = false;
    var     onChange = function () {
                    if (window.recalcFunctions && window.recalcFunctions[aForm.attr("id")])
                    {
                        recalcFunctions[aForm.attr("id")](jqID);
                    }
                    
                    jqID.change();
                };

     jqAutocomplete.autocomplete({
        source: function( request, response ) {
                if (request.term.length < theMinLength)
                {
                    return;
                }
                
                
                var     reqParams = { term: request.term };

                reqParams['varKey'] = $(domElement).attr("data-varkey");
                reqParams['oneit.process.readonly'] = 'true';
                
                if (submitFields == "true")
                {
                    reqParams['FAIL_VALIDATION_ERRORS'] = 'false';                    
                    reqParams = getAllFields (jqAutocomplete, reqParams)
                }
                else
                {
                    reqParams['proc.ID'] = aForm.find("input[name = 'proc.ID']").val();
                    reqParams['proc.stage'] = aForm.find("input[name = 'proc.stage']").val ();
                    reqParams['form.submission'] = aForm.attr('name');
                }

                if (theMinLength == 0)
                {
                    reqParams['limit'] = 2000;
                }
                
                $.ajax({
                        url: $(domElement).attr("data-url"),
                        type: 'POST',
                        dataType: "json",
                        data: reqParams,
                        success: function(data)
                        {
                            response( 
                                $.map( data, function( item ) {return {data_id: item.id, value: item.name, category: item.category, cssClass: item.cssClass};}));
                        },
                        error: function(jqXHR, textStatus, errorThrown)
                        {
                            if(typeof(errorFunction) != 'undefined' && errorFunction !== null)
                            {
                                eval(errorFunction)(jqXHR, textStatus, errorThrown);
                            }
                        }
                 })
            },
        minLength: 0,
        select: function( event, ui ) 
            { 
                jqID.val(ui.item.data_id);
                jqAutocomplete.addClass('autocomplete_activated');
                jqActiveDesc.val(ui.item.value);
                    
                onChange();
                
                if (autosubmitFlag) 
                { 
                    aForm.append("<input name='FAIL_VALIDATION_ERRORS' value='false' style='display: none;'>");
                    aForm.submit(); 
                } 
                
                // Manually trigger a recalc
                onChange();
            },
        change:  function( event, ui ) 
            {
                if(jqAutocomplete.val() == '' || jqAutocomplete.val() == defaultValue )
                {
                    jqID.val('');
                    jqActiveDesc.val('');
                    jqAutocomplete.removeClass('autocomplete_activated');
                }
                else
                {
                    jqAutocomplete.val(jqActiveDesc.val());
                    jqAutocomplete.attr('title', jqActiveDesc.val());
                }
                
                onChange();
            }
    });
    
    var oAutocomplete = jqAutocomplete.data('autocomplete');     
    // override method
    oAutocomplete._renderMenu = function( ul, items ) {
    	var that = this,
	    currentCategory = "";
	    $.each( items, function( index, item ) {
	        if ( item.category && item.category != currentCategory ) {
	            ul.append( "<li class='ui-autocomplete-category ui-menu-item' role='menuitem'>" + item.category + "</li>" );
	            currentCategory = item.category;
	        }
	        that._renderItem(ul, item);
	    });
	};
	
	// original ref to _renderITem method.
	var prevRenderItem = $.ui.autocomplete.prototype._renderItem;
	oAutocomplete._renderItem = function (ul, item)	{
		var $Item = prevRenderItem.apply(this, arguments);
		item.cssClass && $Item.addClass(item.cssClass);
		return $Item;
	};
    
    jqAutocomplete.keydown(function(event) {
            if (event.keyCode == 40 && theMinLength > 0 && $(this).val().length < theMinLength)
            {
                theMinLength = 0;
                jqAutocomplete.autocomplete("search");
            }
        });
    
    if (typeof(window.ontouchstart) != 'undefined')
	{
    	jqAutocomplete.bind ('autocompleteselect', function(event) {
			bSelected = true;
		});
    	
		jqAutocomplete.focus(function(event) {
			
			window.setTimeout(function () {
				if (bSelected)
				{
					bSelected = false;
					return;
				}
			
				theMinLength = 0;
				jqAutocomplete.autocomplete("search");
			}, 1);
		});
	}

}


function eachInitShowProgress()
{
		
		$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
	    $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
	    $("body").append("<div id='TB_load'><img src='" + contextRoot + "/images/loadingAnimation.gif' /></div>");//add loader to the page
	    $('#TB_load').show();//show loader
	
}


function popupOlapTable (popupId, popupJSP, ids)
{
    var thePopup = $('#' + popupId);
    
    thePopup.html ("... Loading ...");
    thePopup.dialog ("open");

    var     idsTxt = ids.join(",");

    $.post (popupJSP, {'ids' : idsTxt}, function (data)
            {
                var     theHTML = data.html;
                thePopup.html (theHTML)
            }, 'json');
            
    return false;
}


function saveOlapTable (uniqueName, pivotConfig)
{
    var  params = { config: JSON.stringify(pivotConfig),
                    dashName: $('.dashboardName' + uniqueName + ' input').val (),
                    tableName: uniqueName };

    ajaxProcessAddJQ ((contextRoot != null ? contextRoot : ".") + "/extensions/dashboard/olap_Dashboard_Save.jsp", "form", params, function () { });
    
    return false;
}


function deleteOlapTable (uniqueName, pivotConfig)
{
    var  params = { config: JSON.stringify(pivotConfig),
                    tableName: uniqueName };

    ajaxProcessDeleteJQ ((contextRoot != null ? contextRoot : ".") + "/extensions/dashboard/olap_Dashboard_Delete.jsp", "form", params);
    
    return false;
}




// This is an array of functions that take a jquery selector and modify it after the HTML has been dynamically added via AJAX
var     postAjaxAddHTMLModifiers = new Array ();
var     postAjaxErrorHandlers    = new Array ();
var     ajaxProgress             = false;
var     ajaxRequestQueue         = new Array ();


function isAJAXInProgress ()
{
    return ajaxProgress;
}


/*
 * An AJAX call has started, lock out any others.
 */
function startAJAXCall ()
{
    log("startAJAXCall");
    ajaxProgress = true;
}


/*
 * An AJAX call has finished.  We might be able to start another.
 */
function endAJAXCall ()
{
    log("endAJAXCall");
    ajaxProgress = false;
    
    if (ajaxRequestQueue.length > 0)
    {
        var deferredFunction = ajaxRequestQueue.shift ();
        
        deferredFunction();
    }
}


/*
 * If an AJAX call is in progress, add it to the queue and it will be called later.
 */
function deferAJAXCall (deferredFunction)
{
    ajaxRequestQueue.push (deferredFunction);
}


function addPostAjaxAddHTMLModifiers (theFunction, runOnLoad)
{
    if (runOnLoad)
    {
        $(document).ready (function () {
                theFunction($(document));
            });
    }
    
    postAjaxAddHTMLModifiers.push(theFunction);
}


function callPostAjaxAddHTMLModifiers (htmlJQ)
{
    for (var x = 0 ; x < postAjaxAddHTMLModifiers.length ; ++x)
    {
        postAjaxAddHTMLModifiers[x](htmlJQ);
    }
}

function addPostAjaxErrorHandler(theFunction)
{
    postAjaxErrorHandlers.push(theFunction);
}


function callPostAjaxErrorHandlers()
{
    for (var x = 0 ; x < postAjaxErrorHandlers.length ; ++x)
    {
        postAjaxErrorHandlers[x]();
    }
}


/*
 * Returns all the name value pairs for the fields on the page.
 * 
 * This will include the form name, since it is a hidden field on the page and so will trigger FPs
 */
function getAllFields (selector, result)
{
    var     toAddTo = $(selector);
    var     aForm = toAddTo.closest('form');
    
    if (!result)
    {
        result = {};
    }

    aForm.find ("input, select, textarea").each (function (index, domElement) { 
            var inputName = $(this).attr("name");

            if (this.type == "checkbox" || this.type == "radio")
            {
                var isChecked = $(this).is(":checked");
                
                if (!isChecked)
                {
                    return;
                }
            }
            
            if (!result[inputName])
            {
                result[inputName] = $(this).val ();
            }
        });
        
    return result;
}


/*
 * Returns the AJAX process params required to push through a request
 */
function ajaxParams (selector, reqParams)
{
    var     toAddTo = $(selector);
    
    if (toAddTo.length != 1)
    {
        window.alert ("Bad ajaxParams selector:" + selector);
    }
    
    var     aForm = toAddTo.closest('form');

    reqParams['proc.ID'] = aForm.find("input[name = 'proc.ID']").val();

    var procStage = aForm.find("input[name = 'proc.stage']").val();
    var formName  = aForm.attr('name');
    
    if(formName == null)
    {
        alert ("Error: AJAX form not found, could be due to an invalid selector");
    }
    
    reqParams['proc.stage'] = procStage;
    reqParams['oneit.process.readonly'] = 'true';
    reqParams['oneit.forceFormName'] = formName;

    return reqParams;
}


function ajaxProcessAdd (page, selector, reqParams, processHTML)
{
    if (!processHTML)
    {
        processHTML = function (theHTML) {
                var htmlJQ = $(theHTML);

                $(toAddTo).append (htmlJQ);
                callPostAjaxAddHTMLModifiers (htmlJQ);
            };
    }

    var     toAddTo = $(selector);
    var     aForm = toAddTo.parents('form');

    ajaxParams (selector, reqParams);

    $.getJSON (page, reqParams, function (data)
            {
                var     theHTML = data.html;
                var     procStage = data.stage;
                if (data.jqExtractor)
                {
                    alert('Please use ajaxProcessAddJQ');
                }    
                  
                processHTML (theHTML, data);
                aForm.find("input[name = 'proc.stage']").val (procStage);
            });
}


function ajaxProcessAddNew (page, selector, reqParams, options)
{
    log("ajaxProcessAddNew", page, selector, reqParams);
    
    var toAddTo = $(selector);
	var defaultOptions = {
	        insertHTML_JQ: function (theHTML_JQ) {
	                                if(theHTML_JQ != null)
	                                {
	                                    $(toAddTo).append (theHTML_JQ);
	                                }
	                            },
	                            
	        onErrorFunction: function (jqXHR, textStatus, errorThrown) {
	                window.alert("Error processing request:" + errorThrown);
	            }, 
	            
	        method: "GET"
	    };
	    
	    
    options = $.extend({}, defaultOptions, options);
    
    var insertHTML_JQ = options.insertHTML_JQ;
    var onErrorFunction = options.onErrorFunction;
    var method = options.method;
    
    
    // lockout to prevent parallel ajax requests
    if (formSubmitting)
    {
        log("ajaxProcessAddNew form is submitting");
        return;
    }
    else if(isAJAXInProgress ())
    {
        log("ajaxProcessAddNew AJAX is in progress");
        // Defer this request and start it later
        deferAJAXCall (function ()  { ajaxProcessAddNew (page, selector, reqParams, options); });
        return;
    }
    
    var     aForm = toAddTo.parents('form');

    ajaxParams (selector, reqParams);
    
    startAJAXCall ();
    
    $.ajax({
            url: page,
            type: method,
            dataType: 'json',
            data: reqParams,
            success: function (data) {
                    var     theHTML    = data.html;
                    var     theHTML_JQ = null;
                    try
                    {
                        if (data.error)
                        {
                            onErrorFunction (null, null, data.error);
                        }

                        try
                        {          
                            theHTML_JQ = $(theHTML);
                        }
                        catch(e)
                        {
                            // Some results can cause problems
                            // Returning empty result also fails here
                            // we will accept this (but the callback may not behave as expected)
                        }

                        var  procStage   = data.stage;
                        var  jqExtractor = data.jqExtractor;

                        if (jqExtractor != null && theHTML_JQ != null)
                        {
                            theHTML_JQ = theHTML_JQ.find (jqExtractor);
                        }

                        insertHTML_JQ(theHTML_JQ);

                        aForm.find("input[name = 'proc.stage']").val (procStage);
                    }
                    catch(e)
                    {
                        onErrorFunction (null, null, e.message);
                    }
                    finally
                    {
                        callPostAjaxAddHTMLModifiers(theHTML_JQ);
                        endAJAXCall ();
                    }
                },
            error: function(jqXHR, textStatus, errorThrown) {
                    callPostAjaxErrorHandlers();
                    onErrorFunction(jqXHR, textStatus, errorThrown);
                    endAJAXCall ();
                }
        });
            
    return false;
}


function ajaxProcessAddJQ (page, selector, reqParams, insertHTML_JQ, onErrorFunction, method)
{
    return ajaxProcessAddNew (page, selector, reqParams, { insertHTML_JQ: insertHTML_JQ, onErrorFunction: onErrorFunction});
}



function ajaxProcessDeleteNew (page, selector, reqParams, options)
{
	var defaultOptions = {
	        deleteHTML_JQ: function (theHTML_JQ) {
	                                theHTML_JQ.remove ();
	                            }
	    };
	    
	    
    options = $.extend({}, options, defaultOptions);
    
    var deleteHTML_JQ = options.deleteHTML_JQ;
    
    // lockout to prevent parallel ajax requests
    if (formSubmitting)
    {
        return;
    }
    else if(isAJAXInProgress ())
    {
        // Defer this request and start it later
        deferAJAXCall (function ()  { ajaxProcessDeleteNew (page, selector, reqParams, options); });
        return;
    }
    
    var     toAddTo = $(selector);
    var     aForm = toAddTo.parents('form');

    ajaxParams (selector, reqParams);
    
    startAJAXCall ();

    $.ajaxSetup({"error":function() 
            {
                endAJAXCall ();
                callPostAjaxErrorHandlers();
            }});

    $.getJSON (page, reqParams, function (data)
            {
                var     theDelete = data.html;
                var     theDelete_JQ = null;
                try
                {
                    try
                    {
                        theDelete = jQuery.trim(theDelete);
                        theDelete_JQ = $(theDelete);
                    }
                    catch(e)
                    {
                        // Some results can cause problems
                        // Returning empty result also fails here
                        // we will accept this (but the callback may not behave as expected)
                    }
    
                    var  procStage   = data.stage;
                    
                    // We set to false & and update the process in case we want to do some more AJAX in the delete function
                    aForm.find("input[name = 'proc.stage']").val (procStage);
                    
                    deleteHTML_JQ (theDelete_JQ);
                    endAJAXCall ();
                }
                finally
                {
                    endAJAXCall ();
                }
            });
            
    return false;
}


function ajaxProcessDeleteJQ (page, selector, reqParams, deleteHTML_JQ)
{
    return ajaxProcessDeleteNew (page, selector, reqParams, { deleteHTML_JQ: deleteHTML_JQ });
}




function ajaxNonProcessReplaceJQ (page, selector, reqParams, insertHTML_JQ)
{
    if (!insertHTML_JQ)
    {
        insertHTML_JQ = function (theHTML_JQ) 
                            {
                                if(theHTML_JQ != null)
                                {
                                    $(toAddTo).html(theHTML_JQ);
                                }
                            };
    }

    var     toAddTo = $(selector);
    
    $.ajaxSetup({"error":function() 
            {
                callPostAjaxErrorHandlers();
            }});

    $.getJSON (page, reqParams, function (data)
            {
                var     theHTML    = data.html;
                var     theHTML_JQ = null;
                try
                {
                    try
                    {
                        theHTML_JQ = $(theHTML);
                    }
                    catch(e)
                    {
                        // Some results can cause problems
                        // Returning empty result also fails here
                        // we will accept this (but the callback may not behave as expected)
                    }
    
                    insertHTML_JQ(theHTML_JQ);
                }
                finally
                {
                    callPostAjaxAddHTMLModifiers(theHTML_JQ);
                }
            });

    return false;
}


var     tableConfigurators = new Array ();


if (jQuery)
{

	
    addPostAjaxAddHTMLModifiers (function (htmlJQ) {
            if(htmlJQ != null)
            {
                if (window.YAHOO) // Do this now, because yui is often not loaded before utils.
                {
                    htmlJQ.find(".yui-date").each(eachInitYUIDate);
                    htmlJQ.find(".yui-date2").each(eachInitYUIDate2);
                }

                if (jQuery.tablesorter)
                {
                    htmlJQ.find (".tablesorter").tablesorter();
                }

                if (jQuery.fn.qtip)
                {
                    htmlJQ.find (".tooltip").qtip({style: {name: 'cream', tip: true}});
                    htmlJQ.find (".tooltipMouse").qtip({style: {name: 'cream', tip: true}, position: {target: 'mouse'}});
                }

                if(jQuery.fn.jqDatePicker)
                    {
                    htmlJQ.find ('.jq-date').jqDatePicker();
                    }

                htmlJQ.find (".ormsingleassoc_autocomplete").each (function (index, domElement) { eachInitiORMSingleAssocAutocomplete (domElement); });

                htmlJQ.find (".ormmultiassoc_autocomplete").each (function (index, domElement) { eachInitORMMultiassocAutocomplete (domElement); });
            }    

            $('.showProgress').click(function () { eachInitShowProgress (); });
        }, true);


    addPostAjaxAddHTMLModifiers (function (htmlJQ) {
            if(htmlJQ != null)
            {
                htmlJQ.find (".autofocus, .autofocus input[type=text]").focus ();
            }
        });

    addPostAjaxAddHTMLModifiers (function (htmlJQ) {
            try
            {
                /*
                 * This is triggered when an ajax add triggers a recalc, which is blocked.
                 * Prevents missing recalc operations.
                 */
                if(htmlJQ != null)
                {
                    var $postRecalcForm = htmlJQ.closest ('form');
                    var $postRecalcFormID = ($postRecalcForm == null) ? null : $postRecalcForm.attr('id');
                
                    if(window.recalcFunctions && window.recalcFunctions[$postRecalcFormID])
                    {
                        recalcFunctions[$postRecalcFormID]();
                    }
                }
            }
            finally
            {
            }
        });

    function getDefaultSorting (theTable)
    {
        var aHeaders = new Object ();

        $(theTable).children ("thead").find ("tr>th").each (function (index, domElement) {
                if ($(this).hasClass ("nosort"))
                {
                    aHeaders[index + ""] = {sorter: false};
                }
            });

        return aHeaders;
    }

    function getDefaultForceSorting (theTable)
    {
        var aForceSort = [];

        $(theTable).children ("thead").find ("tr>th").each (function (index, domElement) {
                if ($(this).hasClass ("tablesorter-force"))
                {
                    aForceSort.push ([index, 0]);
                }
            });

        return aForceSort.length > 0 ? aForceSort : null;
    }

    function getDefaultFilter (theTable)
    {
        var aHeaders = new Object ();

        $(theTable).children ("thead").find ("tr>th").each (function (index, domElement) {
                if ($(this).hasClass ("nofilter") || $(this).closest ("table").hasClass ("nofilter"))
                {
                    aHeaders[index] = {noFilter: true};
                }
            });

        return aHeaders;
    }
    
    function getDefaultExtraction (theTable)
    {
        var aExtractors = "simple";

        $(theTable).children ("thead").find ("tr>th").each (function (index, domElement) {
                if ($(this).hasClass ("iscomplex"))
                {
                    aExtractors = "complex";
                }
            });

        return aExtractors;
    }
    
    tableConfigurators.push (function (domElement, tableSorterConf) {
            tableSorterConf.headers = getDefaultSorting (domElement);
            tableSorterConf.sortForce = getDefaultForceSorting (domElement);
            tableSorterConf.widgets = ['zebra','filterWidget', 'staticRow'];
            tableSorterConf.filterWidget = {columns: getDefaultFilter (domElement)};
            tableSorterConf.textExtraction = getDefaultExtraction (domElement);
        });


    $(document).ready (function () {
    
        log("Document is ready");
    		 //Classy Editor
            $(".classy-editor").each(function(){
            	var editor = $(this);
            	var readonly = editor.prop('readonly');
            	editor.ClassyEdit({
            		readonly: readonly
            	});
            });
            
            //Input Roles
            $('input[type="text"][role]').oneitinputrole();
            
            //TimePicker
            $('input.timepicker').each(function(){
            	var timePicker= $(this);
            	var stepMinute = parseInt(timePicker.attr('data-step-minute'),10);
            	var isReadonly = (typeof timePicker.attr('readonly') !== typeof undefined);
            	if(!isReadonly){
	            	timePicker.timepicker({
	                	stepMinute: stepMinute
	                });
            	}
            });
            
    		imgLoader = new Image();
    		imgLoader.src = contextRoot + "/images/loadingAnimation.gif";
    	
            $("table[data-rowcount]").each (function (index, domElement) {
                var     theTable = $(this);
                var     maxCount = theTable.attr("data-rowcount");
                var     extraRows = theTable.find("tbody>tr:gt(" + (maxCount - 1) + ")");
                
                if (extraRows.length > 0)
                {
                    var     theMoreLinkWrapper = $("<div class='moreLinkWrapper'><a href='#' class='moreLink'>Show all elements</a></div>");
                    var     theMoreLink = theMoreLinkWrapper.find ('a.moreLink');
                    
                    theMoreLink.toggle (
                            function () {theMoreLink.text ("Hide elements");extraRows.show ();return false;},
                            function () {theMoreLink.text ("Show all elements");extraRows.hide ();;return false;}
                        );
                            
                    extraRows.hide ();    
                    theTable.after (theMoreLink);
                }
                
            });
            
            $("table.cougartable").each (function (index, domElement) {
                    var tableSorterConf = {};

                    for (tcIndex in tableConfigurators)
                    {
                        tableConfigurators[tcIndex] (domElement, tableSorterConf);
                    }

                    $(this).tablesorter (tableSorterConf);


                    var     rows = $(domElement).find("tbody>tr[data-link], a.data-link").closest ("tr");
                    
                    rows.hover (
                            function (event) {
                                    $(this).addClass("rowHover");
                                },

                            function (event) {
                                    $(this).removeClass("rowHover");
                                });

                    rows.find ("td").each (function (index, domElement) {
                            var jqThis = $(this);
                            var hasClass = jqThis.hasClass ("noclick");
                            var anyInputsOrLinks = jqThis.find ("input, select, a, textarea");
                            
                            if (!hasClass && anyInputsOrLinks.length == 0)
                            {
                                jqThis.click (function (event) {
                                        var     loc = $(this).closest("tr").attr ("data-link");
                                        var isPopup = false;
                                        if (!loc)
	                                    {
	                                    	var tdLoc = $(this).closest("tr").find ("a.data-link");
	                                        loc = $(tdLoc[0]).attr ("href");
	                                        isPopup = $(tdLoc[0]).hasClass('popup');
	                                    }
                                        if(isPopup)
                                        {
                                            if (typeof loc != 'undefined')
                                            {
                                                window.console.log ("Click");
                                            
                                                var     theDialog = $("#dialog");

                                                //write the iframe code to the above element
                                                theDialog.html ("<iframe class='popup' width='100%' height='100%' src='" + loc + "'>");
                                                theDialog.dialog( "open" ); 
                                                //theDialog.dialog ({ height: 800, width: 900, modal: true });
                                            }
                                            return false;
                                        }else{
                                            if (typeof loc != 'undefined'){
                                                window.location = loc;
                                            }
                                            return false;
                                        }
                                    });
                            }
                        
                            return true;
                        });
                });
                
           
        });
    
    var multiSelectAutoCompleteSelectItemFunc = function(event, ui){
        var jqAutocomplete = $(this);
        jqAutocomplete.addClass('autocomplete_activated');
        
        var selectedValue = ui.item.value,
                    span = $("<span class='multiselect-item'>").text(selectedValue),
                    a = $("<a>").addClass("remove-multi-item").attr({
                href: "javascript:void()",
                title: "Remove " + selectedValue
            }).text("x").appendTo(span);
        
        span.insertBefore($(this));
        $(this).attr("value", "").css("top", 2);
        $(this).val("");
        
        return false;
    }
    function prepareMultiAutoCompleteFeatures(element){
        var autocomplete = $(element);
        var parentDiv = autocomplete.parent('.ormmulti-autocomplete');
        
        parentDiv.find('.multi-autocomplete-input').keydown(function(event) {
            theMinLength = 3
            if (event.keyCode == 40 && theMinLength > 0 && $(this).val().length < theMinLength)
            {
                theMinLength = 0;
                autocomplete.autocomplete("search");
            }
        });
        
        var multiAutocompleteVals = parentDiv.find('.autocomplete_active_desc');
        if(multiAutocompleteVals.val()){
            var currValArray = multiAutocompleteVals.val().split(',');
            for (muItem in currValArray) {
              span = $("<span class='multiselect-item'>").text(currValArray[muItem].trim()),
                    a = $("<a>").addClass("remove-multi-item").attr({
                        href: "javascript:void()",
                        title: "Remove " + currValArray[muItem].trim()
                    }).text("x").appendTo(span);

                    span.insertBefore(autocomplete);
            }
            
            autocomplete.val("").css("top", 2);
        }
        
        parentDiv.click(function(){
        	autocomplete.focus();
        });
    }
    
    $('.ormmulti-autocomplete').find('.remove-multi-item').live('click',function(){
        $(this).parent('span').remove();
    });
}

