var EF_FieldNameIdLookup = new Array();
var __focusObject;
var EFPerformedValidation = false;

function __EFGetFieldValueFromObject(obj1)
{
	var obj = obj1;
	var tmp;

	if (obj != null && obj.value)
	{
		tmp = parseFloat(obj.value);
		if (! isNaN(tmp))
			return tmp;
		else
			return 0;
	}
	else if (obj != null && obj.options)
	{
		//for option fields
		var count;
		for (count = 0; count < obj.options.length; count++)
		{
			if (obj.options[count].checked)
			{
				tmp = parseFloat(obj.value);
				if (! isNaN(tmp))
					return tmp;
				else
					return 0;
			}
		}
	} 
	else if (obj != null && obj.innerText)
	{
		tmp = parseFloat(obj.innerText);
		if (! isNaN(tmp))
			return tmp;
		else
			return 0;	
	}
	else if (obj != null && obj.innerHTML)
	{
		tmp = parseFloat(obj.innerHTML);
		if (! isNaN(tmp))
			return tmp;
		else
			return 0;
	}
	else
	{
		return 0;
	}

}

//GET a float value from a field.
//if field value contain a non-number, zero is returned
function __EFGetFieldValue(fieldId)
{
	var obj = document.getElementById(fieldId);
	
	if (obj != null)
	{
		return __EFGetFieldValueFromObject(obj);
	}
	else
	{
		return 0;
	}
}

//SET a given value to a form field
function __EFSetFieldValue(fieldId, fieldValue)
{	
	var obj = document.getElementById(fieldId);

	if (obj != null)
	{
		//alert(obj);
		if (obj.value)
		{
			//alert('Value');
			obj.value = fieldValue;
		}
		else if(obj.innerText || obj.innerText == '')
		{
			obj.innerText = fieldValue;
		}
		else if (obj.innerHTML)
		{
			//alert('HTML ' + fieldValue);
			obj.innerHTML = fieldValue;
		}
		else
		{
			//alert('Text ' + fieldValue);
			obj.innerText = fieldValue;
		}
	}
}

function __EFGetElementFromCache(id)
{
	//determines if already stored in lookup cache
	var cachedId = EF_FieldNameIdLookup[id];
	var obj = null;
	
	if (cachedId != null && cachedId != '')	
	{
		//load get from id
		obj = document.getElementById(cachedId);
		
		if (obj != null)
			return obj;
		else
			return null;
	}

	return null;

}

function __EFGetElementByIDByTag(id, tag)
{
	//load from cache first
	var obj = __EFGetElementFromCache(id);
	
	if (obj != null)
		return obj;

	//try all input boxes first
	var aInputs = document.getElementsByTagName(tag);
	
	//alert(id + " " + tag + ' ' + aInputs.length);
	
	for(index = 0; index < aInputs.length; index++)
	{
	
		if (aInputs[index].id)
		{
			//alert(aInputs[index].id);
			if (aInputs[index].id.indexOf(id) > -1)
			{
				//alert('FOUND');
				//set to cache
				EF_FieldNameIdLookup[id] = aInputs[index].id;
				
				return aInputs[index];
			}
		}
	}

	return null;
}

function __EFGetElementByID(id)
{
	//try all input boxes first
	var obj;
	
	obj = __EFGetElementByIDByTag(id, "INPUT");
	
	if (obj != null)
		return obj;

	obj = __EFGetElementByIDByTag(id, "SELECT");
	
	if (obj != null)
		return obj;

	obj = __EFGetElementByIDByTag(id, "TEXTAREA");
	
	if (obj != null)
		return obj;
		
	obj = __EFGetElementByIDByTag(id, "SPAN");
	
	if (obj != null)
		return obj;


	obj = __EFGetElementByIDByTag(id, "DIV");
	
	if (obj != null)
		return obj;

	//radio/checkbox list element
	obj =__EFGetElementByIDByTag(id, "TABLE");
	
	if (obj != null)
	{
		EF_FieldNameIdLookup[id] = '';
		return __EFLoadListOptions(obj);
	}

	return null;
}


function __EFGetElementByEFFieldNameByTag(fieldname, tag)
{

	//load from cache first
	var obj = __EFGetElementFromCache(fieldname);
	
	if (obj != null)
		return obj;
		
		
	//try all input boxes first
	var aInputs = document.getElementsByTagName(tag);
	
	//alert(fieldname + " " + tag + ' ' + aInputs.length);
	
	for(index = 0; index < aInputs.length; index++)
	{
		//alert(aInputs[index].getAttribute("effieldname") + ' = ' + fieldname);
		
		if (aInputs[index].getAttribute("effieldname") != null)
		{
			if (aInputs[index].getAttribute("effieldname") == fieldname)
			{
				//set to cache
				EF_FieldNameIdLookup[fieldname] = aInputs[index].id;

				return aInputs[index];
			}
		}
		else
		{
			var parentNode = aInputs[index].parentNode;
					
			if (parentNode != null && typeof(parentNode.getAttribute) != "undefined")
			{
				if (parentNode.getAttribute("effieldname") != null && parentNode.getAttribute("effieldname") == fieldname)
				{
					//set to cache
					EF_FieldNameIdLookup[fieldname] = aInputs[index].id;

					return aInputs[index];
				}
			}
		}
	}

	return null;
}


function __EFGetElementByEFFieldName(fieldname)
{
	//try all input boxes first
	var obj;
	
	//alert(fieldname);

	obj = __EFGetElementByEFFieldNameByTag(fieldname, "INPUT");
	
	if (obj != null)
		return obj;
		
		
	obj = __EFGetElementByEFFieldNameByTag(fieldname, "SPAN");
	
	if (obj != null)
		return obj;

	obj = __EFGetElementByEFFieldNameByTag(fieldname, "SELECT");
	
	if (obj != null)
		return obj;

	obj = __EFGetElementByEFFieldNameByTag(fieldname, "TEXTAREA");
	
	if (obj != null)
		return obj;

	obj = __EFGetElementByEFFieldNameByTag(fieldname, "DIV");
	
	if (obj != null)
		return obj;

	//radio/checkbox list element
	obj = __EFGetElementByEFFieldNameByTag(fieldname, "TABLE");
	
	if (obj != null)
	{
		//reset cache
		EF_FieldNameIdLookup[fieldname] = '';
		return __EFLoadListOptions(obj);
	}

	return null;
}

function __EFRedirect(url)
{
	location.href = url;
	return true;
}

//function to compare values of two fields
//if matched returns true else display errMsg value and returns false
function __EFCompareValues(efFielA, efFieldB, errMsg)
{
	var objA = __EFGetElementByEFFieldName(efFielA);
	var objB = __EFGetElementByEFFieldName(efFieldB);
	
	//exit if one of the two fields do not exists
	if (objA == null || objB == null)
	{
		return true;
	}
	
	if (objA.value == objB.value)
	{
		return true;
	}
	else
	{
		__EFAlert(errMsg);
		return false;
	}
}

//displays message if not empty
function __EFAlert(message)
{
	if (message != null && message != '')
		alert(message);
}

//load objects from checkbox list and radio lists
function __EFLoadListOptions(obj)
{
	var list = new Array();  //stores array of list options
	var count = 0; //counter
	
	if (obj == null)
		return obj;
	
	while(true)
	{
		var listObj = document.getElementById(obj.id + '_' + count);
		if (listObj != null)
		{
			list[count] = listObj;
			count++;
		}
		else
		{
			break;
		}
	}
	
	return list;	
}

///////////////////////////////////////

function __EFFocusDelay(fieldId)
{
    __focusObject = document.getElementById(fieldId);
    if (__focusObject != null && ! __focusObject.disabled)
        window.setTimeout("__focusObject.focus()", 700);
}

function __EFRegisterFieldFocus(field)
{
    jQuery('input#EFFocusIDHolder').val(field.id);
}


function __EFDisableBtn(btnID) {

    //Page_IsValid = null;
    var isValidationOk = false;
    var causeValidation = false;

    var btn = jQuery('#' + btnID);

    if (btn == null)
        return false;

    if (btn.attr('efvalidation') != null){
        //alert('cause validation');
        causeValidation = true;
    }
    
    if (causeValidation && typeof (Page_ClientValidate) == 'function') {
        Page_ClientValidate();
        EFPerformedValidation = true;
        isValidationOk = Page_IsValid;
    } else {
        //alert('not using validation ' + EFPerformedValidation);
        if (isDefined('Page_IsValid') && Page_IsValid !== null)
        {                  
            if (Page_IsValid && EFPerformedValidation && typeof (Page_ClientValidate) == 'function') {
                //alert('validate again');
                Page_ClientValidate();
                isValidationOk = Page_IsValid;    
            } else 
                isValidationOk = Page_IsValid;
            
            //alert('page valid is not null');
        }
        else {
            //alert('page valid is NULL');
            isValidationOk = true;
        }
    }
    
    
    if (isValidationOk !== null || isValidationOk){
        //check custom script
        var customscript = btn.attr("customscript");
        
        if (customscript != null && customscript != ''){
            //alert(isValidationOk + ' custom script: ' + customscript);
            isValidationOk = eval(customscript);
            //alert(isValidationOk);
        }
    } 

    if (isValidationOk !== null) {
        if (isValidationOk) {
            //__EFSetAjaxImage(btnID);
            setTimeout("__EFSetAjaxImage('"+btnID+"')", 20);
            return true;
        }
        else {
            return false;
        }
    }
    else {
        setTimeout("__EFSetAjaxImage('"+btnID+"')", 20);
        return true;
    }
}

function __EFSetAjaxImage(elementId) {

    var buttonId = '';
    var imgId = '';
    var otherId = '';

    if (elementId.indexOf('EFActionButton') > 0) {
        //determines id of button and images for submit buttons
        if (elementId.indexOf('EFActionButtonImg') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('EFActionButtonImg', 'EFActionButton');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('EFActionButton', 'EFActionButtonImg');
        }
    } else if (elementId.indexOf('FirstActive') > 0) {
        //determines id of button and images for first page button
        if (elementId.indexOf('imgFirstActive') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('imgFirstActive', 'lnkFirstActive');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('lnkFirstActive', 'imgFirstActive');
        }
    } else if (elementId.indexOf('PrevActive') > 0) {
        //determines id of button and images for previous page button
        if (elementId.indexOf('imgPrevActive') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('imgPrevActive', 'lnkPrevActive');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('lnkPrevActive', 'imgPrevActive');
        }
    } else if (elementId.indexOf('NextActive') > 0) {
        //determines id of button and images for next page button
        if (elementId.indexOf('imgNextActive') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('imgNextActive', 'lnkNextActive');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('lnkNextActive', 'imgNextActive');
        }
    } else if (elementId.indexOf('LastActive') > 0) {
        //determines id of button and images for last page button
        if (elementId.indexOf('imgLastActive') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('imgLastActive', 'lnkLastActive');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('lnkLastActive', 'imgLastActive');
        }
    } else if (elementId.indexOf('ResetForm') > 0) {
        //determines id of button and images for reset button
        if (elementId.indexOf('imgResetForm') > 0) {
            imgId = elementId;
            buttonId = elementId.replace('imgResetForm', 'lnkResetForm');
        } else {
            buttonId = elementId;
            imgId = elementId.replace('lnkResetForm', 'imgResetForm');
        }
    } else {
        buttonId = '';
        imgId = '';
        otherId = elementId;
        //alert('other: ' + otherId);
    }
        
    var btn = null;
    var img = null;
    var other = null;
    
    if (buttonId != null && buttonId != '')
        btn = jQuery('#' + buttonId);
        
    if (imgId != null && imgId != '')
        img = jQuery('#' + imgId);
        
    if (otherId != null && otherId != '')
        other = jQuery('#' + otherId);
    
    //alert(buttonId + ' ' + btn + ' ' + imgId + ' ' + img + ' ' + otherId + ' ' + other);
    if (btn != null && img != null) {
        //alert('image is NOT null');
        //alert(img.attr('src') + '    ' + EFAJAXButtonImage);
        if (img.attr('src') != null){        
            img.attr('src', EFAJAXButtonImage);
            img.attr('disabled', 'disabled');
            btn.css('display', 'none');
        } else {
            btn.removeAttr("href");
            btn.html("<img src='" + EFAJAXImage + "' style='width:70px;' />");
        }
    } else if (btn != null && img == null) {   
        //alert('image is null');
        btn.removeAttr("href");
        btn.html("<img src='" + EFAJAXImage + "' style='width:70px;' />");
    } else if (other != null) {
        //alert('here ' + EFAJAXImage);
        other.css("background-image", "url('" + EFAJAXButtonImage + "')");
        other.css("background-repeat", "no-repeat");
        //other.css("background-position", "50% 0%");
    }
    
    //need to disable other postback fields
    jQuery("input[efpostback], a[efpostback]").each(function(){
        jQuery(this).attr('disabled', 'disabled');
        jQuery(this).unbind("click");
        jQuery(this).bind("click", function(){
            alert('Disabled');
            return false;
        });                
    });    
    
    jQuery("input[efevent], select[efevent], textarea[efevent], span[efevent] > input, table[efevent] input").each(function(){
        jQuery(this).attr('disabled', 'disabled');
              
    });  
}

/////////////////////////////////////
//debug
/////////////////////////////////////
function isDefined(variable)
{
    return eval('(typeof(' + variable+ ') != "undefined");');
}

function printProps(obj, objName) {
  var output = "" ;
  for (var prop in obj) {
    output += objName + "." + prop + " = " + obj[prop] + "\n" ;
  }
  return output ;
}

function EFLogConsole(str)
{
    if (isDefined('console'))
        console.log(str);
}

/////////////////////////////////////
//functions assocated with dnn.getVar
/////////////////////////////////////

function EFIsTooltipEnabled()
{
    if (isDefined('dnn') && dnn.getVar('EFTooltipEnabled') == '1')
        return true;
    if (isDefined('EFTooltipEnabled') && EFTooltipEnabled == 1)
        return true;
    else
        return false;
}

function EFIsInEditFormMode()
{
    if (isDefined('dnn') && dnn.getVar('EFFormEditMode') == '1')
        return true;
    else
        return false;
}

function EFShowEditFormElementMetadata()
{
    if (isDefined('dnn') && dnn.getVar('EFElementToolip') == '1')
        return true;
    else
        return false;
}

function EFDragDropEnabled()
{
    if (isDefined('dnn') && dnn.getVar('EFFormDragDrop') == "1")
        return true;
    else
        return false;
}

function EFApplicationPath()
{
    if (isDefined('dnn'))
        return dnn.getVar('EFWSPath');
    else
        return "./";
}

function EFIsViewFormPage()
{
    if (isDefined('dnn') && dnn.getVar('EFViewFormPage') == '1')
        return true;
    else
        return false;
}

/////////////////////////////////////
//template manager listings
/////////////////////////////////////
function __EFShowPreview(titleId, previewUrl, width, height)
{
    var id = "span#" + titleId;
    var caption = EFPreviewTitle + ': ' + jQuery("#" + titleId).html();
    displayModalBoxFixed(caption, EFApplicationPath() + previewUrl, width, height);
}

function __EFShowPreview2(title, previewUrl, width, height)
{
    var caption = EFPreviewTitle + ': ' + title;
    displayModalBoxFixed(caption, EFApplicationPath() + previewUrl, width, height);
}


function __EFInitShowPreview() {
    jQuery(document).ready(function() {
        jQuery('tr[PreviewUrl]').dblclick(function(){
            var obj = jQuery(this);
            
            var previewUrl = obj.attr('PreviewUrl');
            var titleId = obj.attr('TitleId');
            
            __EFShowPreview(titleId, previewUrl, 450, 500);
            
        });
    });
}

/////////////////////////////////////
//template manager listings
/////////////////////////////////////

function setCookie(name, value, expires) {
    document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
} 

function setCookie30Days(name, value) {
    var exp = new Date();     //set new date object
    exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
    setCookie(name, value, exp);
} 


/////////////////////////////////////
//client grids
/////////////////////////////////////
function PopulateTemplateGrid(gridId, pagerId, filterId, viewtype, sidx, sord, currentPage, pageSize, previewUrl, editUrl, headerText, pagerText, recordText, noRecordText, locale)
{
    //EFLogConsole('headers: ' + headerText);
    jQuery(document).ready(function(){

        jQuery("#" + gridId).jqGrid({
            datatype: function(dataToPost) {
            
                var filter = jQuery("#" + filterId);
                
                //if (filter != null)
                //    EFLogConsole(filterId + ' ' + filter.val());
                //else
                //    EFLogConsole('unable to locate filter field');
                
                var postData = "{'key':'" + dnn.getVar('EFWSAuthId') + "'"; 
                postData += ",'rows':" + dataToPost.rows + "";  
                postData += ",'page':" + dataToPost.page + "";  
                postData += ",'sidx':'" + dataToPost.sidx + "'";  
                postData += ",'sord':'" + dataToPost.sord + "'";      
                postData += ",'viewtype':'" + viewtype + "'";      
                postData += ",'filter':'" + filter.val() + "'"; 
                postData += ",'locale':'" + locale + "'";        
                postData += "}"; 
                
                //EFLogConsole(postData);
                //EFLogConsole(EFApplicationPath());
               
                jQuery.ajax({
                    type: "POST",
                    url: EFApplicationPath() + "/EntFormsWS.asmx/GetDesignerTemplates?tabid=" + dnn.getVar('EFTabId'),
                    data: postData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        if (msg != '')
                        {
                            var message = '';
                            if (typeof msg == 'object')
                                message = msg['d'];
                            else
                                message = msg;
                            
                            if (msg == null || msg == '')
                                return; 
                                
                            //EFLogConsole(message);
                            
                            var thegrid = jQuery("#" + gridId);
                                                    
                            var jsonobj = eval('(' + message + ')');


                            thegrid[0].addJSONData(jsonobj);
                                   
                        }
                   },
                   complete: function() {
                        endGridRequest(gridId);  
                   },
                   beforeSend: function(message){
                        beginGridRequest(gridId);
                   }
                   
                });
            },
            ondblClickRow: function(rowid) {
            
                var caption = jQuery("#" + gridId).getCell(rowid, 'title');
                var url = previewUrl;
                url = url.replace('XXX', rowid);
                
                __EFShowPreview2(caption, url, 450, 500);
            
            },
            onSortCol: function(index, iCol, sortorder){
            
                EFLogConsole(index + ' ' + sortorder);
                setCookie30Days('EF_TEMPLATE_SORT', index + ' ' + sortorder);
            
            },
            onPaging: function(pgButton) {
            
                var page = jQuery("#" + gridId).getGridParam('page');
                EFLogConsole('Selected Page Index: ' + page);
                setCookie('EF_TG_INDEX', page);
            
            },
            gridComplete: function() {
                //set css class to normalize with DNN skins
                //jQuery("th[role='columnheader']").addClass("SubHead");
                //jQuery("td[role='gridcell']").addClass("Normal");
                
                
                var theGrid = jQuery("#" + gridId);
                //convert first column to link buttons                
                var dataIds = theGrid.getDataIDs();
                //EFLogConsole('DataIds: ' + dataIds + ' length: ' + dataIds.length + ' EditUrl: ' + editUrl);
                var i = 0;
                var currentPage = theGrid.getGridParam('page');
                for (i = 0; i < dataIds.length; i++)
                {
                    var title = theGrid.getCell(dataIds[i], 'title');
                    //alert(title);
                    var onclick = '__EFShowPreview2("' + title + '", "' + previewUrl.replace('XXX', dataIds[i]) + '", 450, 500);';
                    //EFLogConsole('Onclick: ' + onclick);
                    var editLink = "<a href='" + editUrl.replace('XXX', dataIds[i]).replace('PPP', currentPage) + "'><img style='border-width:0px' src='" + EFApplicationPath() + "/images/Edit-16x16.gif" + "'/></a>";
                    var previewLink = "<a onclick='" + onclick + "'><img style='border-width:0px' src='" + EFApplicationPath() + "/images/Preview-16x16.gif" + "'/></a>";
                    //EFLogConsole('FormId: ' + dataIds[i] + ' Editlink: ' + editLink + ' PreViewLink: ' + previewLink);
                    
                    theGrid.setCell(dataIds[i], "Links", editLink + '&nbsp;' + previewLink);
                }
                
            },

   	        colNames: eval(headerText),
   	        colModel:[
   		        {name:'Links',index:'links',sortable:false,width:'75px'},
   		        {name:'title',index:'title'},
   		        {name:'owner',index:'owner'},
   		        {name:'state_name',index:'state_name'},		
   		        {name:'lockby',index:'lockby'},		
   		        {name:'formtype',index:'formtype',width:'75px'},				
   		        {name:'create_tstamp',index:'create_tstamp'},	   		       		    
   		        {name:'update_tstamp',index:'update_tstamp'},	
   		        {name:'version',index:'version',width:'75px'}	   		       		    
   	        ],
   	        page: currentPage,
   	        pager: '#' + pagerId,
   	        rowNum: pageSize,
   	        altRows: false,
   	        sortname: sidx,
            sortorder: sord,
            autowidth: true,
            multiselect: false, 
            shrinkToFit: true,
            forceFit: true,
            viewrecords: true,
            width: '100%',
            height: '100%',
            recordtext: recordText,
            pgtext: pagerText,
            loadtext: '<img style="border-width:0px" src="' + EFApplicationPath() + '/images/button-ajax-loader.gif"/>',
            emptyrecords: noRecordText,
            width: '100%'
        });
        
        jQuery("#" + gridId).jqGrid('navGrid','#' + pagerId, {edit:false, add:false, del:false, search:false, loadui:'block'});

    });
}

function beginGridRequest(gridName) {
    //EFLogConsole('begin request');
    var ts = jQuery("#" + gridName + ".ui-jqgrid-btable")[0];
    ts.grid.hDiv.loading = true;
    if (ts.p.hiddengrid) { return; }
    switch (ts.p.loadui) {
        case "disable":
            break;
        case "enable":
            jQuery("#load_" + ts.p.id).show();
            break;
        case "block":
            jQuery("#lui_" + ts.p.id).show();
            jQuery("#load_" + ts.p.id).show();
            break;
    }
}

function endGridRequest(gridName) {
    //EFLogConsole('request completed');
    var ts = jQuery("#" + gridName + ".ui-jqgrid-btable")[0];
    ts.grid.hDiv.loading = false;
    if (ts.p.hiddengrid) { return; }
    switch (ts.p.loadui) {
    case "disable":
        break;
    case "enable":
        jQuery("#load_" + ts.p.id).hide();
        break;
    case "block":
        jQuery("#lui_" + ts.p.id).hide();
        jQuery("#load_" + ts.p.id).hide();
        break;
    }
}


function PopulateInstanceGrid(gridId, pagerId, filterId, ids, sinfo, sidx, sord, currentPage, pageSize, editUrl, headerText, pagerText, recordText, noRecordText, locale)
{
    jQuery(document).ready(function(){

        jQuery("#" + gridId).jqGrid({
            datatype: function(dataToPost) {
                
                var filterObj = null;
                var filter = '';
                                
                if (filterId != null && filterId != '')
                    filterId =jQuery("#" + filterId);

                if (filterObj != null)
                    filter = filterObj.val();
                
                var postData = "{'key':'" + dnn.getVar('EFWSAuthId') + "'"; 
                postData += ",'ids':'" + ids + "'";  
                postData += ",'rows':" + dataToPost.rows + "";  
                postData += ",'page':" + dataToPost.page + "";  
                postData += ",'sidx':'" + dataToPost.sidx + "'";  
                postData += ",'sord':'" + dataToPost.sord + "'";      
                postData += ",'sinfo':'" + sinfo + "'";      
                postData += ",'filter':'" + filter + "'"; 
                postData += ",'locale':'" + locale + "'";        
                postData += "}"; 
                
                EFLogConsole(postData);
                //EFLogConsole(EFApplicationPath());
               
                jQuery.ajax({
                    type: "POST",
                    url: EFApplicationPath() + "/EntFormsWS.asmx/GetTemplateInstances?tabid=" + dnn.getVar('EFTabId'),
                    data: postData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        if (msg != '')
                        {
                            var message = '';
                            if (typeof msg == 'object')
                                message = msg['d'];
                            else
                                message = msg;
                            
                            if (msg == null || msg == '')
                                return; 
                                
                            //EFLogConsole(message);
                            
                            var thegrid = jQuery("#" + gridId);
                                                    
                            var jsonobj = eval('(' + message + ')');

                            thegrid[0].addJSONData(jsonobj);
                            
                                    
                        }
                   },
                   complete: function() {
                        endGridRequest(gridId);  
                   },
                   beforeSend: function(message){
                        beginGridRequest(gridId);
                   }
                   
                });
            },
            onSortCol: function(index, iCol, sortorder){
                EFLogConsole(index + ' ' + sortorder);
                setCookie30Days('EF_WF_SORT', index + ' ' + sortorder);
            },
            onPaging: function(pgButton) {
                //var page = jQuery("#" + gridId).getGridParam('page');
                //EFLogConsole('Selected Page Index: ' + page);
                //setCookie('EF_TG_INDEX', page);
            },
            gridComplete: function() {
                //set css class to normalize with DNN skins
                //jQuery("th[role='columnheader']").addClass("SubHead");
                //jQuery("td[role='gridcell']").addClass("Normal");
                
                var theGrid = jQuery("#" + gridId);
                //convert first column to link buttons                
                var dataIds = theGrid.getDataIDs();
                //EFLogConsole('DataIds: ' + dataIds + ' length: ' + dataIds.length + ' EditUrl: ' + editUrl);
                var i = 0;
                var currentPage = theGrid.getGridParam('page');
                for (i = 0; i < dataIds.length; i++)
                {
                    var formid = theGrid.getCell(dataIds[i], "formid");
                    var editLink = "<a href='" + editUrl.replace('XXX', dataIds[i]).replace('PPP', currentPage).replace('YYY', formid) + "'><img style='border-width:0px' src='" + EFApplicationPath() + "/images/Edit-16x16.gif" + "'/></a>";
                    
                    theGrid.setCell(dataIds[i], "Links", editLink);
                }
            },

   	        colNames: eval(headerText),
   	        colModel:[
   		        {name:'Links',index:'links',sortable:false,width:'35px'},
   		        {name:'form',index:'title'},
   		        {name:'instanceid',index:'instance_id',width:'35px'},
   		        {name:'owner',index:'owner'},		
   		        {name:'state',index:'state_name'},						
   		        {name:'create_tstamp',index:'create_tstamp'},	   		       		    
   		        {name:'update_tstamp',index:'update_tstamp'},	   		       		    
   		        {name:'formid',index:'formid',sortable:false,hidden:true}	   		       		    
   	        ],
   	        page: currentPage,
   	        pager: '#' + pagerId,
   	        rowNum: pageSize,
   	        altRows: false,
   	        sortname: sidx,
            sortorder: sord,
            autowidth: true,
            multiselect: false, 
            shrinkToFit: true,
            forceFit: true,
            viewrecords: true,
            width: '100%',
            height: '100%',
            recordtext: recordText,
            pgtext: pagerText,
            loadtext: '<img style="border-width:0px" src="' + EFApplicationPath() + '/images/button-ajax-loader.gif"/>',
            emptyrecords: noRecordText
        });
        
        jQuery("#" + gridId).jqGrid('navGrid','#' + pagerId, {edit:false, add:false, del:false, search:false, loadui:'block'});

    });
}


function PopulateReportGrid(gridId, pagerId, ids, sinfo, sidx, sord, currentPage, pageSize, editUrl, colNames, colModels, pagerText, recordText, noRecordText, showDetailLink, hidePaging, locale)
{
    jQuery(document).ready(function(){

        jQuery("#" + gridId).jqGrid({
            datatype: function(dataToPost) {

                var postData = "{'key':'" + dnn.getVar('EFWSAuthId') + "'"; 
                postData += ",'id':'" + ids + "'";  
                postData += ",'sinfo':'" + sinfo + "'";   
                postData += ",'rows':" + dataToPost.rows + "";  
                postData += ",'page':" + dataToPost.page + "";  
                postData += ",'sidx':'" + dataToPost.sidx + "'";  
                postData += ",'sord':'" + dataToPost.sord + "'";      
                postData += ",'locale':'" + locale + "'";        
                postData += "}"; 
                
                EFLogConsole(postData);
                //EFLogConsole(EFApplicationPath());
               
                jQuery.ajax({
                    type: "POST",
                    url: EFApplicationPath() + "/EntFormsWS.asmx/GetReportInstances?tabid=" + dnn.getVar('EFTabId'),
                    data: postData,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                        if (msg != '')
                        {
                            var message = '';
                            if (typeof msg == 'object')
                                message = msg['d'];
                            else
                                message = msg;
                            
                            if (msg == null || msg == '')
                                return; 
                                
                            //EFLogConsole(message);
                            
                            var thegrid = jQuery("#" + gridId);
                                                    
                            var jsonobj = eval('(' + message + ')');

                            thegrid[0].addJSONData(jsonobj);
                            
                                    
                        }
                   },
                   complete: function() {
                        endGridRequest(gridId);  
                   },
                   beforeSend: function(message){
                        beginGridRequest(gridId);
                   }
                   
                });
            },
            onSortCol: function(index, iCol, sortorder){
                //EFLogConsole(index + ' ' + sortorder);
                //setCookie30Days('EF_WF_SORT', index + ' ' + sortorder);
            },
            onPaging: function(pgButton) {
            },
            gridComplete: function() {               
                var theGrid = jQuery("#" + gridId);
                
                if (showDetailLink)
                {
                    //convert first column to link buttons                
                    var dataIds = theGrid.getDataIDs();
                    //EFLogConsole('DataIds: ' + dataIds + ' length: ' + dataIds.length + ' EditUrl: ' + editUrl);
                    var i = 0;
                    var currentPage = theGrid.getGridParam('page');
                    for (i = 0; i < dataIds.length; i++)
                    {
                        var histid = dataIds[i];
                        var instanceid = theGrid.getCell(dataIds[i], "tmpid");
                        
                        var editLink = "<a href='" + editUrl.replace('III', instanceid).replace('PPP', currentPage).replace('HHH', histid) + "'><img style='border-width:0px' src='" + EFApplicationPath() + "/images/Edit-16x16.gif" + "'/></a>";
                        
                        theGrid.setCell(dataIds[i], "Links", editLink);
                    }
                }
                else
                    theGrid.hideCol('Links');
                    
                //if (theGrid.getGridParam("records") == '1')
                if (hidePaging)
                    jQuery('#' + pagerId).hide();
            },

   	        colNames: eval(colNames),
   	        colModel: eval(colModels),
   	        page: currentPage,
   	        pager: '#' + pagerId,
   	        rowNum: pageSize,
   	        altRows: false,
   	        sortname: sidx,
            sortorder: sord,
            autowidth: true,
            multiselect: false, 
            shrinkToFit: false,
            forceFit: false,
            viewrecords: true,
            width: 'auto',
            height: '100%',
            recordtext: recordText,
            pgtext: pagerText,
            loadtext: '<img style="border-width:0px" src="' + EFApplicationPath() + '/images/button-ajax-loader.gif"/>',
            emptyrecords: noRecordText
        });
        
        jQuery("#" + gridId).jqGrid('navGrid','#' + pagerId, {edit:false, add:false, del:false, search:false, loadui:'block'});

    });
}

function EFConfirm(msg, obj)
{
    jConfirm(msg, 'Confirmation', function(r){
        if (r)
            __doPostBack(obj.id.replace(/_/g, '$'), '');
    });
    
    return false;
}

function EFConfirm2(msg, obj)
{
    jConfirm(msg, 'Confirmation', function(r){
        if (r)
            window.location = jQuery('#' + obj.id).attr('href');
    });
    
    return false;
}