var currentBKNGridRows;
var currentBKNGrid;
var winModalDialog;
function WaitWindowIsClosed(expresion) 
{ 
	if (winModalDialog.closed)
	{
		eval(expresion); 
	}
	else
	{
	    setTimeout('WaitWindowIsClosed("' + expresion + '")',500);
	}
} 
function SelectBKNRow(popUpUrl, hddId, txtBoxId, cellId, cellText, IsRequired)
{
	if(window.showModalDialog)
	{	
		currentBKNGridRows = window.showModalDialog(popUpUrl,'','dialogHeight:600px;dialogWidth=800px;scroll:no;status:no;resizable:yes');
		SetBKNRowInfo(currentBKNGridRows, hddId, txtBoxId, cellId, cellText, IsRequired);
		throwEvent_CloseWindow();
	}
	else
	{
		winModalDialog  = window.open(popUpUrl,'','modal=yes,height=600,width=800,scrollbars=no,status=no');
		WaitWindowIsClosed('SetBKNRowInfo(currentBKNGridRows,\'' + hddId + '\',\'' + txtBoxId + '\',' + cellId + ',' + cellText + ',' + IsRequired +');throwEvent_CloseWindow();');
	}
}

function throwEvent_CloseWindow()
{
    try
    {
        if (Unload_window != "")
        {
            Unload_window();
        }
    }
    catch (e)
    {
    }
}

function openModalDialog(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh)
{
    var vRetModal = false;
    if(popUpUrl == null || popUpUrl == "")
    {
        return;
    }
    
    if(width == null || width == 0)
    {
        width = 600;
    }
    
    if(height == null || height == 0)
    {
        height = 300;
    }
    
    if(scroollbars == null || scroollbars == "")
    {
        scroollbars == 'no';
    }
    
    var top = (screen.height/2)-(height/2);
    var left = (screen.width/2)-(width/2);
    /*BCRMDialog = new ComponentArt_Dialog('BCRMDialog',height,width,dlg1); 

    BCRMDialog.set_contentUrl(popUpUrl);
    BCRMDialog.set_modal(true);
    BCRMDialog.SetProperty('parent',parent);
    BCRMDialog.set_minimumHeight(height);
    BCRMDialog.set_minimumWidth(width);
    BCRMDialog.SetProperty('Height',height);
    BCRMDialog.SetProperty('Width',width);
    BCRMDialog.set_allowResize(false);
    BCRMDialog.Initialize();
    BCRMDialog.show();*/
    
    if(window.showModalDialog)
    {
        var vRet = window.showModalDialog(popUpUrl,self,'dialogHeight:' + height + 'px;dialogWidth=' + width + 'px;dialogTop=' + top + 'px;dialogLeft=' + left + 'px;scroll:'+ scroollbars +';status:no;resizable:yes');
        if(theGridToRefresh != null){theGridToRefresh.Callback();}else{if(windowParentRefresh != null){parentWindowRefresh(windowParentRefresh);}}
        if(vRet != undefined)
        {
            vRetModal = vRet;
        }
    }
    else
    {
        winModalDialog = window.open(popUpUrl,'','modal=yes,height=' + height + ',width=' + width + ',top=' + top + ',left=' + left + ',scrollbars='+ scroollbars +',status=no');
        var expresion;
        if(theGridToRefresh != null)
        {
           expresion = theGridToRefresh.Id + '.Callback();';
        }
        else if(windowParentRefresh != null)
        {
            
            expresion = 'parentWindowRefresh(' + windowParentRefresh + ');';
        }
        WaitWindowIsClosed(expresion);
    }
    
    return vRetModal;
}

function OpenModalDialogWithOpenCollapse(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh,
    openCollapseButtonClientObjectName)
{
    if(openCollapseButtonClientObjectName != null
            && openCollapseButtonClientObjectName != '')
    {
        eval(openCollapseButtonClientObjectName).Open();
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if(prm != null)
    {
        waitForOpenModalDialog(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh);
    }
    else
    {
        return openModalDialog(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh);
    }
       
    
}

function waitForOpenModalDialog(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh)
{
   var prm = Sys.WebForms.PageRequestManager.getInstance();
    if(prm != null)
    {
        if(prm.get_isInAsyncPostBack())
        {
            setTimeout("waitForOpenModalDialog('" + popUpUrl + "','" + width + "','" + height + "','" + scroollbars + "','" + windowParentRefresh + "','" + theGridToRefresh + "')",250);        
        }
        else
        {
            return openModalDialog(popUpUrl, width, height, scroollbars, windowParentRefresh, theGridToRefresh);
        }
    }
}
    


function parentWindowRefresh(windowRefresh)
{
	if(windowRefresh)window.location.href = window.location.href;
}

function SetBKNRowInfo(rows, hddId, txtBoxId, cellId, cellText, IsRequired)
{
	var theHiddenBox = document.getElementById(hddId);
	var theTextBox = document.getElementById(txtBoxId);
	if(rows)
	{
		if(rows.length  != 0)
		{
			theHiddenBox.value = rows[0].Cells[cellId].Value;
			theTextBox.value = rows[0].Cells[cellText].Value;
			return true;
		}
	}
	
	theHiddenBox.value = '00000000-0000-0000-0000-000000000000';
	
	if(IsRequired)
	{
		theTextBox.value = '';
	}
	else
	{
		theTextBox.value = '--';
	}
	return false;
}

function SelectGridRowsFromPopUpWithOpenCollapse(popUpUrl, theGrid, scroollbars, openCollapseButtonClientObjectName)
{
    if(openCollapseButtonClientObjectName != null
            && openCollapseButtonClientObjectName != '')
    {
	    eval(openCollapseButtonClientObjectName).Open();
	}
	
	return SelectGridRowsFromPopUp(popUpUrl, theGrid, scroollbars);
}

function SelectGridRowsFromPopUp(popUpUrl, theGrid, scroollbars)
{
	currentBKNGrid = theGrid;
	currentBKNGridRows = null;
	if(scroollbars == null)scroollbars = 'no';
	if(window.showModalDialog)
	{	
		currentBKNGridRows = window.showModalDialog(popUpUrl,'','dialogHeight:560px;dialogWidth=750px;scroll:'+ scroollbars +';status:no;resizable:yes');
		ProcessReceivedData(currentBKNGrid,currentBKNGridRows);
		
	}
	else
	{
		var left = (screen.width/2)-(750/2);
	    var top = (screen.height/2)-(560/2);
	    	    
		winModalDialog  = window.open(popUpUrl,'','left=' + left + ',top=' + top + ',modal=yes,height=560,width=750,menubar=no,scrollbars='+ scroollbars +',status=no,resizable=yes');
		WaitWindowIsClosed('ProcessReceivedData(currentBKNGrid,currentBKNGridRows)');
	}
}
function ProcessReceivedData(theGrid,theRows)
{
	if(theRows)
	{
		if(theRows.length  != 0)
		{
			var i=0;
			for(i;i<theRows.length;i++)
			{
				if(!theRows[i])
				{
					continue;
				}
				existRow = null;
				existRow = theGrid.GetRowFromKey(0,theRows[i].Cells[0].Value);
				if(existRow == null)
				{
					theGrid.Table.AddEmptyRow();
					theRow = theGrid.Table.GetRow(theGrid.Table.GetRowCount()-1);
					theGrid.Edit(theRow);
					theRow.SetValue(0,theRows[i].Cells[0].Value,false);
					theGrid.EditComplete(false);
				}
			}
			theGrid.Callback();
			theGrid.Render();
			return true;
		}
	}
	else
    {
        theGrid.Callback();
    }
	return false;
}
function CheckAllElements(grid, columnNumber, theCheck)
{
    var gridItem;
    var itemIndex = 0;
    var value = grid.Table.GetRow(itemIndex).Cells[columnNumber].Value;
	while(gridItem = grid.Table.GetRow(itemIndex))
    {
		gridItem.SetValue(columnNumber, !value);
		itemIndex++;
    }
    grid.Render();
}

 function deleteGridRow(theGrid, rowId)
 {
		var theGridObject = eval(theGrid);
		var therow = theGridObject.GetRowFromClientId(rowId);
		theGridObject.deleteItem(therow); 
	//	theGridObject.Callback();
 }
 function TakeOwnershipRow(theGrid, rowId)
{
		callbackCommand(theGrid,'TakeOwner',rowId);
}
 function callbackCommand(theGrid, commandName, rowId)
{
	var item;
	if(rowId != null && rowId != '')
	{
		item = theGrid.GetRowFromClientId(rowId);
	}
	else
	{
		item = theGrid.Table.GetRow(0);
	}
	theGrid.edit(item);
	for(ix=0;ix<theGrid.Table.Columns.length;ix++)
	{
		if(theGrid.Table.Columns[ix].DataField == (theGrid.Id + '_command'))
		{
			item.setValue(ix, commandName,false);
			break;
		}
	}
	theGrid.editComplete();
	theGrid.callback();
}

function onGroupingChange(sender, eventArgs)
{
  // event handler logic goes here
  // eventArgs is of GridSortEventArgs type
  if(parent.autofitIframe != null)
  {
      setTimeout("parent.autofitIframe('Main',this);",1000);
  }      
}

function editGrid(theGrid, rowId, isNew)
{
    if(isNew == false)
    {
        theGrid.Table.Columns[9].set_allowEditing(false);
    }
    theGrid.Edit(theGrid.GetRowFromClientId(rowId)); 
}

function onUpdate(oldItem, newItem)
{
     if (newItem.Data[3] == "")
    {
            alert('El nombre no puede estar vacio.');
            return false;
    }
	else if ((eval(newItem.Table.Grid.Id).RecordCount > 1) && (newItem.GetMember('Success')!= null))
	{
        var success = 0;
        var count = eval(oldItem.Table.Grid.Id).RecordCount - 1;
        for (var i = 0; i <= count; i++) 
        {
            if(oldItem.Table.Grid.Levels[0].Table.Data[i][6] == true) // 6 => ColumName --> "Success"
            {
            		if (newItem.GetMember('OpportunityStageId')!=null)
            		{
	                    if (newItem.GetMember('OpportunityStageId').Value != oldItem.Table.Grid.Levels[0].Table.Data[i][4])
	                    {
	                        success++;    
	                    }
	            	}    
	            	else 
	            	{
	            	    success++;
	            	}
            }
        }
        if (success < 1 && newItem.GetMember('Success').Value == false)
        {
            alert("Al menos una etapa de la oportunidad debe implicar éxito.");
            return 2;
        }
    }
     
    if(document.all!= null) //if IE
    {
        if((event != null) && (event.keyCode==13))
        {
            return false;
        }
        else 
        {
            return true;
        }
    }
    else    //if Firefox (no esta implementado el evento "pinchar la tecla Enter")
    {
        return true;        
    }               
}
function editRow(theGrid)
{    
    theGrid.EditComplete();
}

function editDGCancel(theGrid)
{
	theGrid.EditCancel();
}                               

var _cancelCallback = false;

function onUpdateCampaign(oldItem, newItem)
{
    _cancelCallback = false;
    if (campaignAvaiableStatus[newItem.GetMember('CampaignTargetStateId').Value][1]=='True')
    {
        if (campaignAvaiableStatus[newItem.GetMember('CampaignTargetStateId').Value][0] == 'Rejected'
            || campaignAvaiableStatus[newItem.GetMember('CampaignTargetStateId').Value][0] == 'Unsuscribe')
        {
            //a final Status selected, solicitate confirmation
            if (confirm("Has seleccionado '" + campaignAvaiableStatus[newItem.GetMember('CampaignTargetStateId').Value][2] + "'. ¿Estás seguro de que el destinatario ha rechazado recibir publicidad? No podrás cambiarlo después."))
		    {			
			    //validates, save.
			    return 1;
		    }
		    // failed validation, return to editing
		    _cancelCallback = true;
		    return 2; 
		}
		else
		{
		    //a final Status selected, solicitate confirmation
            alert ("Has seleccionado '" + campaignAvaiableStatus[newItem.GetMember('CampaignTargetStateId').Value][2] + "'. Este estado no se puede asignar manualmente.");
            
		    _cancelCallback = true;
		    return 2; 
		}
	}
	else
	{
	    return 1; //Save, a non final Status selected
	}
}


function campaignEditRow(theGrid, rowId)
{    
	theGrid.EditComplete(false);
	
	if(!_cancelCallback)
	{
	    theGrid.Callback();
	}
}

function configEditRow(theGrid, rowId)
{    
	theGrid.EditComplete();
	
	if(!_cancelCallback)
	{
	    theGrid.Callback();
	}
}

function SelectionInfo(currentGrid,
    additionalCallbackGrids,
    notificationEvent)
{
    this.currentGrid = currentGrid;
    this.additionalCallbackGrids = additionalCallbackGrids;
    this.selectionCancelled = true;
    this.refreshCurrentGrid = false;
    this.refreshAdditionalCallbackGrids = false;
    this.selectedElementId = null;
    this.selectedElementName = null;
    this.notificationEvent = notificationEvent;
        
    this.RaiseNotificationEvent = function()
    {
        if(this.notificationEvent == null)
        {
            return;
        }
        
        eval(this.notificationEvent)(this);
    }
}

var _selectionInfo = null;

function OpenSelectionPopUpWithOpenCollapse(popUpUrl,
    theGrid,
    scroollbars,
    additionalCallbackGrids,
    openCollapseButtonClientObjectName)
{
    if(openCollapseButtonClientObjectName != null
            && openCollapseButtonClientObjectName != '')
    {
        eval(openCollapseButtonClientObjectName).Open();
    }
    
    return OpenSelectionPopUp(popUpUrl,
        theGrid,
        scroollbars,
        additionalCallbackGrids);
}

function OpenSelectionPopUp(popUpUrl,
    theGrid,
    scroollbars,
    additionalCallbackGrids,
    notificationEvent)
{
    _selectionInfo = new SelectionInfo(theGrid,
        additionalCallbackGrids,
        notificationEvent);
    
	if(scroollbars == null)
	{
	    scroollbars = 'no';
	}
	
	if(window.showModalDialog)
	{	
		window.showModalDialog(popUpUrl,
		    _selectionInfo,
		    'dialogHeight:560px;dialogWidth=750px;scroll:'+ scroollbars +';status:no;resizable:yes');
		    
		ProcessPopUpSelection();
	}
	else
	{
	    var left = (screen.width/2)-(750/2);
	    var top = (screen.height/2)-(560/2);
	    	    
		winModalDialog  = window.open(popUpUrl,'','left=' + left + ',top=' + top + ',modal=yes,height=560,width=750,menubar=no,scrollbars='+ scroollbars +',status=no,resizable=yes');
		WaitWindowIsClosed('ProcessPopUpSelection()');
	}
}

function ProcessPopUpSelection()
{
    if(_selectionInfo == null
            || !(_selectionInfo instanceof SelectionInfo)
            || _selectionInfo.selectionCancelled)
    {
        return;
    }
    
    if(_selectionInfo.additionalCallbackGrids == null
            || _selectionInfo.refreshAdditionalCallbackGrids == null
            || _selectionInfo.refreshAdditionalCallbackGrids == false)
    {
        if(_selectionInfo.refreshCurrentGrid)
        {
            _selectionInfo.currentGrid.Callback();
            
            _selectionInfo.RaiseNotificationEvent();
            return;
        }
    }
    
    if(_selectionInfo.additionalCallbackGrids != null
            && _selectionInfo.additionalCallbackGrids.length > 1
            && _selectionInfo.refreshCurrentGrid)
    {
        parentWindowRefresh(true); //It would be slower to force callbacks than to reload the page.
        _selectionInfo.RaiseNotificationEvent();
        return;
    }
    
    if(_selectionInfo.refreshCurrentGrid)
    {
        _selectionInfo.currentGrid.Callback();
    }
    
    if(_selectionInfo.additionalCallbackGrids == null)
    {
        _selectionInfo.RaiseNotificationEvent();
        return;
    }
    
    for(var i = 0;i < _selectionInfo.additionalCallbackGrids.length;++i)
    {
        eval(_selectionInfo.additionalCallbackGrids[i]).Callback();
    }
    
    _selectionInfo.RaiseNotificationEvent();
}

function CollapseGrid(gridObject,
            itemTypeName,
            showGridScriptCode)
{
    var elements = eval(gridObject).RecordCount;
    var HTML;
    var integerNumberFormatInfo = new numberFormatInfo(myNumberFormatInfo.thousandSeparator,
                                                    myNumberFormatInfo.decimalsSeparator,
                                                    myNumberFormatInfo.secondDecimalsSeparator,
                                                    0);
                
    if(elements == 0)
    {
        HTML = '<center><table cellpadding="1" cellspacing="2px" border="0">' +
                '<tr>' +
                    '<td>' +
                        '<span class="text">No hay ' + itemTypeName + ' para mostrar en este listado.</span>' +
                    '</td>' +
                '</tr>' +
                '</table></center>';
                
                
    }
    else
    {
        HTML = '<center><table cellpadding="1" cellspacing="2px" border="0">' +
                '<tr>' +
                    '<td>' +
                        '<span class="text">Hay ' + new Number(eval(gridObject).RecordCount).convertToStringFormatted(integerNumberFormatInfo) + ' ' + itemTypeName + ' en este listado.</span><span class="link" style="cursor:pointer" onclick="javascript:' + showGridScriptCode + '.Open();">Haz clic aquí para mostrar el listado</span><span class="text">.</span>' +
                    '</td>' +
                '</tr>' +
                '</table></center>';
    }
    
    autofitIframe('Main',this);
    
    return HTML;
}
function OpenGrid(panelObject, gridObject, forceReload, expression)
{
    if(document.getElementById(gridObject) == null || forceReload)
    {
        __doPostBack(panelObject,'');
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    expression = 'autofitIframe(\'Main\',this);' + expression;
    if((prm != null && prm.get_isInAsyncPostBack()) || (document.ComponentArt_Page_Loaded != null && document.ComponentArt_Page_Loaded == false))
    {
        setTimeout('WaitAsyncEnd("' + expression + '","' + gridObject + '");',500);
    }
    else
    {
        eval(gridObject).Render();
        setTimeout('eval("' + expression + '");',200);
        return;
    }    
}
function WaitAsyncEnd(expression, gridObject)
{
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if((prm != null && prm.get_isInAsyncPostBack()) || (document.ComponentArt_Page_Loaded != null && document.ComponentArt_Page_Loaded == false))
    {
         setTimeout('WaitAsyncEnd("' + expression + '","' + gridObject + '");',500);
    }
    else
    {
        if(document.getElementById(gridObject) == null || document.ComponentArt_Page_Loaded == false)
        {
            alert('Ha ocurrido un error al cargar los datos.');
        }
        else
        {
            eval(gridObject).Render();
            setTimeout('eval("' + expression + '");',200);
        }
    }
    
}
function Grid_onLoad(sender, eventArgs)
{
    autofitIframe('Main',this);
}
