{if $strMsjResponse != ""}
    <div class="ui-widget">
	<div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
            <p>
                <br/>
                <span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
                <strong>Informaci&oacute;n!</strong>
                {$strMsjResponse}
                <br/>
            </p>
	</div>
    </div>
{/if}

<script type='text/javascript' src='{sugar_getjspath file='include/javascript/popup_helper.js'}'></script>


<script>
{literal}
    $(document).ready(function(){
        $("ul.clickMenu").each(function(index, node){
            $(node).sugarActionMenu();
        });

        $('.selectActionsDisabled').children().each(function(index) {
            $(this).attr('onclick','').unbind('click');
        });

        var selectedTopValue = $("#selectCountTop").attr("value");
        if(typeof(selectedTopValue) != "undefined" && selectedTopValue != "0"){
            sugarListView.prototype.toggleSelected();
        }
    });
{/literal}	
</script>
{assign var="currentModule" value = $pageData.bean.moduleDir}
{assign var="singularModule" value = $moduleListSingular.$currentModule}
{assign var="moduleName" value = $moduleList.$currentModule}
{assign var="hideTable" value=false}
{if count($data) == 0}
    {assign var="hideTable" value=true}
    <div class="list view listViewEmpty">
        {if $displayEmptyDataMesssages}
            {if strlen($query) == 0}
                {capture assign="createLink"}<a href="?module={$pageData.bean.moduleDir}&action=EditView&return_module={$pageData.bean.moduleDir}&return_action=DetailView">{$APP.LBL_CREATE_BUTTON_LABEL}</a>{/capture}
                {capture assign="importLink"}<a href="?module=Import&action=Step1&import_module={$pageData.bean.moduleDir}&return_module={$pageData.bean.moduleDir}&return_action=index">{$APP.LBL_IMPORT}</a>{/capture}
                {capture assign="helpLink"}<a target="_blank" href='?module=Administration&action=SupportPortal&view=documentation&version={$sugar_info.sugar_version}&edition={$sugar_info.sugar_flavor}&lang=&help_module={$currentModule}&help_action=&key='>{$APP.LBL_CLICK_HERE}</a>{/capture}
                <p class="msg">
                    {$APP.MSG_EMPTY_LIST_VIEW_NO_RESULTS|replace:"<item2>":$createLink|replace:"<item3>":$importLink}
                </p>
                <p class="submsg">
                    {$APP.MSG_EMPTY_LIST_VIEW_NO_RESULTS_SUBMSG|replace:"<item1>":$moduleName|replace:"<item4>":$helpLink}
                </p>
            {elseif $query == "-advanced_search"}
                <p class="msg">
                    {$APP.MSG_LIST_VIEW_NO_RESULTS_BASIC}
                </p>
            {else}
                <p class="msg">
                    {capture assign="quotedQuery"}"{$query}"{/capture}
                    {$APP.MSG_LIST_VIEW_NO_RESULTS|replace:"<item1>":$quotedQuery}
                </p>
                <p class = "submsg">
                    <a href="?module={$pageData.bean.moduleDir}&action=EditView&return_module={$pageData.bean.moduleDir}&return_action=DetailView">
                        {$APP.MSG_LIST_VIEW_NO_RESULTS_SUBMSG|replace:"<item1>":$quotedQuery|replace:"<item2>":$singularModule}
                    </a>
                </p>
            {/if}
        {else}
            <p class="msg">
                {$APP.LBL_NO_DATA}
            </p>
        {/if}
    </div>
{/if}
{$multiSelectData}
{if $hideTable == false}
    <table cellpadding='0' cellspacing='0' width='100%' border='0' class='list view'>
        {assign var="link_select_id" value="selectLinkTop"}
        {assign var="link_action_id" value="actionLinkTop"}
        {assign var="actionsLink" value=$actionsLinkTop}
        {assign var="selectLink" value=$selectLinkTop}
        {assign var="action_menu_location" value="top"}
        {include file='include/ListView/ListViewPagination.tpl'}
        <!--header titles--->
	<tr height='20'>
            {if $prerow}
                <td width='1%' class="td_alt">
                    &nbsp;
                </td>
            {/if}
            {if !empty($quickViewLinks)}
                <td class='td_alt' width='1%' style="padding: 0px;">&nbsp;</td>
            {/if}
            {counter start=0 name="colCounter" print=false assign="colCounter"}
            {foreach from=$displayColumns key=colHeader item=params}
                <th scope='col' width='{$params.width}%'>
                    <div style='white-space: normal;'width='100%' align='{$params.align|default:'left'}'>
	                {if $params.sortable|default:true}
	                    {if $params.url_sort}
	                        <a href='{$pageData.urls.orderBy}{$params.orderBy|default:$colHeader|lower}' class='listViewThLinkS1'>
	                    {else}
	                        {if $params.orderBy|default:$colHeader|lower == $pageData.ordering.orderBy}
	                            <a href='javascript:sListView.order_checks("{$pageData.ordering.sortOrder|default:ASCerror}", "{$params.orderBy|default:$colHeader|lower}" , "{$pageData.bean.moduleDir}{"2_"}{$pageData.bean.objectName|upper}{"_ORDER_BY"}")' class='listViewThLinkS1'>
	                        {else}
	                            <a href='javascript:sListView.order_checks("ASC", "{$params.orderBy|default:$colHeader|lower}" , "{$pageData.bean.moduleDir}{"2_"}{$pageData.bean.objectName|upper}{"_ORDER_BY"}")' class='listViewThLinkS1'>
	                        {/if}
	                    {/if}
	                    {sugar_translate label=$params.label module=$pageData.bean.moduleDir}
                                &nbsp;&nbsp;
                                {if $params.orderBy|default:$colHeader|lower == $pageData.ordering.orderBy}
                                    {if $pageData.ordering.sortOrder == 'ASC'}
                                        {capture assign="imageName"}arrow_down.{$arrowExt}{/capture}
                                        {capture assign="alt_sort"}{sugar_translate label='LBL_ALT_SORT_DESC'}{/capture}
                                        {sugar_getimage name=$imageName attr='align="absmiddle" border="0" ' alt="$alt_sort"}
                                    {else}
                                        {capture assign="imageName"}arrow_up.{$arrowExt}{/capture}
                                        {capture assign="alt_sort"}{sugar_translate label='LBL_ALT_SORT_ASC'}{/capture}
								{sugar_getimage name=$imageName attr='align="absmiddle" border="0" ' alt="$alt_sort"}
                                    {/if}
                                {else}
                                    {capture assign="imageName"}arrow.{$arrowExt}{/capture}
                                    {capture assign="alt_sort"}{sugar_translate label='LBL_ALT_SORT'}{/capture}
                                    {sugar_getimage name=$imageName attr='align="absmiddle" border="0" ' alt="$alt_sort"}
                                {/if}
                            </a>
                            {else}
                                {if !isset($params.noHeader) || $params.noHeader == false} 
                                    {sugar_translate label=$params.label module=$pageData.bean.moduleDir}
                                {/if}
                            {/if}
                        </div>
                </th>
                {counter name="colCounter"}
            {/foreach}
            <td class='td_alt' nowrap="nowrap" width='1%'>&nbsp;</td>
        </tr>
			
        {counter start=$pageData.offsets.current print=false assign="offset" name="offset"}
        {assign var=counter value=0 print=false}
        {foreach name=rowIteration from=$data key=id item=rowData}
            {counter name="offset" print=false}
            {assign var='scope_row' value=true}
            {if $smarty.foreach.rowIteration.iteration is odd}
                {assign var='_rowColor' value=$rowColor[0]}
            {else}
                {assign var='_rowColor' value=$rowColor[1]}
            {/if}
            <tr height='20' class='{$_rowColor}S1'>
                {if $prerow}
/*
        <tr class='pagination'  role='presentation'>
		<td colspan='{if $prerow}{$colCount+1}{else}{$colCount}{/if}'>
			<table border='0' cellpadding='0' cellspacing='0' width='100%' class='paginationTable'>
*/
                    <td width='1%' class='nowrap'>
                        {if !$is_admin && is_admin_for_user && $rowData.IS_ADMIN==1}
                            <input type='checkbox' disabled="disabled" class='checkbox' value='{$rowData.ID}'>
                        {else}
                            <input title="{sugar_translate label='LBL_SELECT_THIS_ROW_TITLE'}" onclick='sListView.check_item(this, document.MassUpdate); fnchkDesChkAll(this);' type='checkbox' class='checkbox' name='mass[]' id='chkrowtpl-{$counter}' value='{$rowData.ID}'>
                        {/if}
                    </td>
                {/if}
                {if !empty($quickViewLinks)}
                    {capture assign=linkModule}{if $params.dynamic_module}{$rowData[$params.dynamic_module]}{else}{$pageData.bean.moduleDir}{/if}{/capture}
                    {capture assign=action}{if $act}{$act}{else}EditView{/if}{/capture}
                    <td width='2%' nowrap>
                        {if $pageData.rowAccess[$id].edit}
                            <!--<a title='{$editLinkString}' id="edit-{$rowData.ID}"
                                href="index.php?module=Contacts&offset={$offset}&stamp={$pageData.stamp}&return_module={$linkModule}&action={$action}&record={$rowData.ID}"
                            >
                            {capture name='tmp1' assign='alt_edit'}{sugar_translate label="LNK_EDIT"}{/capture}
                            {sugar_getimage name="edit_inline.gif" attr='border="0" ' alt="$alt_edit"}</a>
                            -->
                        {/if}
                    </td>
                {/if}
                {counter start=0 name="colCounter" print=false assign="colCounter"}
                {foreach from=$displayColumns key=col item=params}
                    {strip}
                    <td {if $scope_row} scope='row' {/if} align='{$params.align|default:'left'}' valign="top" class="{if ($params.type == 'teamset')}nowrap{/if}{if preg_match('/PHONE/', $col)} phone{/if}">
                        
                            {if $col == 'NAME' || $params.bold}<b>{/if}
/*
				<tr>
					<td nowrap="nowrap" width='2%' class='paginationActionButtons'>
						{if $prerow}

                        {sugar_action_menu id=$link_select_id params=$selectLink}
	
	
*/
                            {if $params.link && !$params.customCode}
                                {capture assign=linkModule}{if $params.dynamic_module}{$rowData[$params.dynamic_module]}{else}{$params.module|default:$pageData.bean.moduleDir}{/if}{/capture}
                                {capture assign=action}{if $act}{$act}{else}DetailView{/if}{/capture}
                                {capture assign=record}{$rowData[$params.id]|default:$rowData.ID}{/capture}
                                {if $col == 'FIRST_NAME'}
                                    {capture assign=url}index.php?module=Contacts&offset={$offset}&stamp={$pageData.stamp}&return_module={$linkModule}&action={$action}&record={$record}{/capture}
                                {else}
                                    {capture assign=url}index.php?module={$linkModule}&offset={$offset}&stamp={$pageData.stamp}&return_module={$linkModule}&action={$action}&record={$record}{/capture}
                                {/if}
                                <{$pageData.tag.$id[$params.ACLTag]|default:$pageData.tag.$id.MAIN} href="{sugar_ajax_url url=$url}">
                            {/if}
                            {if $params.customCode} 
                                {sugar_evalcolumn_old var=$params.customCode rowData=$rowData}
                            {else}	
                                {sugar_field parentFieldArray=$rowData vardef=$params displayType=ListView field=$col}
                            {/if}
                            {if empty($rowData.$col) && empty($params.customCode)}&nbsp;{/if}
                            {if $params.link && !$params.customCode}
                                </{$pageData.tag.$id[$params.ACLTag]|default:$pageData.tag.$id.MAIN}>
                            {/if}
                            {if $col == 'NAME' || $params.bold}</b>{/if}
                    </td>
                    {/strip}
                    {assign var='scope_row' value=false}
                    {counter name="colCounter"}
                {/foreach}
                <td align='right'>{$pageData.additionalDetails.$id}</td>
            </tr>
        {capture assign=var}{$counter++}{/capture}
        {foreachelse}
            <tr height='20' class='{$rowColor[0]}S1'>
                <td colspan="{$colCount}">
                    <em>{$APP.LBL_NO_DATA}</em>
                </td>
            </tr> 
        {/foreach}
        <tr>
                <td colspan="9"></td>
                <td><b id="total2"></b></td>
                <td><b id="total1"></b></td>
            </tr>
            {assign var="link_select_id" value="selectLinkBottom"}
            {assign var="link_action_id" value="actionLinkBottom"}
            {assign var="selectLink" value=$selectLinkBottom}
            {assign var="actionsLink" value=$actionsLinkBottom}
            {assign var="action_menu_location" value="bottom"}
            {include file='include/ListView/ListViewPagination.tpl'}
/*
						{sugar_action_menu id=$link_action_id params=$actionsLink}

                        { if $actionDisabledLink ne "" }<div class='selectActionsDisabled' id='select_actions_disabled_{$action_menu_location}'>{$actionDisabledLink}<span class='ab'></span></div>{/if}
						&nbsp;{$selectedObjectsSpan}		
					</td>
                                       </tr>
                        </table>     
                </td> 
        </tr>       
                                       
                                       
                                        
        
 
*/
	</table>
{/if}
{if $contextMenus}
<script type="text/javascript">
{$contextMenuScript}
{literal}
function lvg_nav(m,id,act,offset,t){
    if(t.href.search(/#/) < 0){return;}
    else{
        if(act=='pte'){
            act='ProjectTemplatesEditView';
        }
        else if(act=='d'){
            act='DetailView';
        }else if( act =='ReportsWizard'){
            act = 'ReportsWizard';
        }else{
            act='EditView';
        }
    {/literal}
        url = 'index.php?module='+m+'&offset=' + offset + '&stamp={$pageData.stamp}&return_module='+m+'&action='+act+'&record='+id;
        t.href=url;
    {literal}
    }
}{/literal}
{literal}
    function lvg_dtails(id){{/literal}
        return SUGAR.util.getAdditionalDetails( '{$pageData.bean.moduleDir|default:$params.module}',id, 'adspan_'+id);{literal}
    }
{/literal}
</script>

{/if}
<div id="divOculto" style="display:none;">
    <div id="divConfigCampania" title="Configuaracion de Campaña">
        <div id="divPreloadConfigCampania" style="color:red;font-family:verdana;"></div>
        <div id="divBodyConfigCampania">
            <form id="frmConfigCampania" enctype="multipart/form-data"  method="post" action='index.php?module=COMM1_communications'>
                <input type="hidden" id="action" name="action" value="salvarCampania"/>
                <input type="hidden" id="hdnidscontacts" name="hdnidscontacts" />
               <input type="hidden" id="hdnidscontacts" name="hdnidscontacts" value="{$contatsIdList}"/> 
                <input type="hidden" id="hdnBolCamposCruzar" name="hdnBolCamposCruzar" value="false"/>
                <div>
                    Cant. Seleccionados:
                    <span id="spnCountRowsSend" style="color:red;">0</span>
                    <br/>
                    Nombre campa&ntilde;a:<br/>
                    <input type='text' id='txtNombreCampania' name='txtNombreCampania' size='40'/>
                    <br/>
                    Tipo:
                    <select id="selTipoCampania" name="selTipoCampania">
                        <option value="">Seleccione...</option>
                        <option value="EMAIL">Email</option>
                        <option value="SMS">SMS</option>
                        <option value="WHATSAPP">Whatsapp</option>
                    </select>
                    <a href="javascript:void(0)" onclick="fnShowHelpDatos();"><img src="themes/default/images/help.gif" title="Datos de ayuda" /></a>
                    Fecha envio: 
                    <input id="txtFechaExecute" name="txtFechaExecute" type="text" size="15" readonly="readonly" />
                </div>
                <div id="divEmail" style="display:none;">
                    <fieldset>
                        <legend>Configurar EMAIL</legend>
                        Tipo email: 
                        <select id="selTipoEMAIL" name="selTipoEMAIL">
                            <option value="PLANTILLA">Plantilla</option>
                            <option value="ABIERTO">Texto abierto</option>
                        </select>
                        <div id="divTemplatesEMAIL">
                            Plantillas disponibles: 
                            <select id="selPlantillaBdEMAIL" name="selPlantillaBdEMAIL">
                                <option value="">Seleccione...</option>
                                {foreach from=$dataListTemplates key=colHeader item=params}
                                    <option value="{$params.id}">{$params.name}</option>
                                {/foreach}
                            </select>
                            <span id="spnEditTEmplateEMAIL">
                                <a href="javascript:void(0)" onclick="fnRedirectEditarTemplate();">Editar</a>
                            </span>
                            <br/>
                            <fieldset>
                                <legend>Previsualizaci&oacute;n</legend>
                                <br/>
                                <div id="divPreviewTemplateEMAIL"></div>
                                <br/><br/>
                            </fieldset>
                        </div>
                        <div id="divAbiertoEMAIL" style="display:none;">
                            Texto email: 
                            <textarea id="tarTextoAbiertoEMAIL" name="tarTextoAbiertoEMAIL" rows="15" cols="40"></textarea>
                        </div>
                    </fieldset>
                </div>
                <div id="divSms" style="display:none;">
                    <fieldset>
                        <legend>Configurar SMS</legend>
                        Mensaje:
                        <textarea id="tarMsjSMS" name="tarMsjSMS" rows="10" cols="30"></textarea>
                        <span id="spnCountCaractSMS" style="color:red;">(0/160)</span>
                    </fieldset>
                </div>
                <div id="divWhatsapp" style="display:none;">
                    <fieldset>
                        <legend>Configurar Whatsapp</legend>
                        <!--Bloquear foto whatsapp swsw imagen hasta <br/>-->
                        Imagen:
                        <input type="file" id="img1WHATSAPP" name="img1WHATSAPP"/>
                        <br/>
                        Mensaje:
                        <textarea id="tarMsjWHATSAPP" name="tarMsjWHATSAPP" rows="10" cols="30"></textarea>
                    </fieldset>
                </div>
                <br/>
                Observaciones:
                <br/>
                <textarea id='tarObsCampania' name='tarObsCampania' cols="50" rows="5"></textarea>
            </form>
        </div>
    </div>
    <div id="divHelpDatos">
        <div>
            <p>
                <b>Campos posibles para agregar y que se pueden reemplazar<br/> 
                   por datos del CONTACTO en BASE DE DATOS:</b>
            </p>
            <div>
                Nombres: [first_name]<br/>
                Apellidos: [last_name]<br/>
                Tel&eacute;fono celular: [phone_mobile]<br/>
                Identificaci&oacute;n: [cedula_nit_c]<br/>
            </div>
        </div>
    </div>
    <select id="selTiendasHidden">
        <option value="">TODAS</option>
        {foreach from=$dataListStuTiendas key=colHeader item=params}
            <option value="{$params.id}">{$params.name}</option>
        {/foreach}
    </select>
</div>

<div id='divHistorialReporteCallcenter' title='Reporte de Campañas'>
    <ul>
        <li><a href='#divReport1'>Reportes</a></li>
        <li><a href='#divReport2'>Reportes2</a></li>
    </ul>
    <!-- 
       agregado por:darwin rosero 
      se agrega este div para la nueva pestaña  -->
    <div id='divReport1'>
    
        <div id="divPreloadReport1" style="color:red;font-family:verdana;"></div>
        <div>
            <table border=0>
                <tr>
                    <td>
                        Campaña:
                    </td>
                    <td>
                        <select class="selCampanaTab1"  name="selCampana">
                            <option value="Beneficios">Beneficios</option>
                            <option value="Colecciones">Colecciones</option>
                            <option value="Promociones">Promociones</option>
                            <option value="Todas">Todas</option>
                        </select>
                    </td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>    
                        Ciudad:
                    </td>
                    <td>
                        <select class="selCiudadTab1"  name="selCiudad">
                            <option value="noselmes">Seleccionar una Ciudad</option>
                            <option value="Cali">Cali</option>
                            <option value="Medellin">Medellin</option>
                            <option value="Pereira">Pereira</option>
                            <option value="Manizales">Manizales</option>
                            <option value="Bogota">Bogota</option>
                            <option value="Amazonas">Amazonas</option>
                        </select>
                    </td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>
                        Tipo Campaña:
                    </td>
                    <td>
                        <select class="selTipoCampanaTab1" name="selTipoCampana" >
                            <option value="EMAIL">EMAIL</option>
                            <option value="SMS">SMS</option>
                            <option value="Whatsapp">Whatsapp</option>
                            <option value="Todas">Todas</option>
                        </select>           
                    </td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>
                        Fecha:
                        <select class="selMesTab1" name="selMes" >
                            <option value="noselmes">Seleccionar un Mes</option>
                            <option value="enero">Enero</option>
                            <option value="febrero">Febrero</option>
                            <option value="marzo">Marzo</option>
                            <option value="abril">Abril</option>
                            <option value="mayo">Mayo</option>
                            <option value="junio">Junio</option>
                            <option value="julio">Julio</option>
                            <option value="agosto">Agosto</option>
                            <option value="septiembre">Septiembre</option>
                            <option value="octubre">Octubre</option>
                            <option value="noviembre">Noviembre</option>
                            <option value="diciembre">Diciembre</option>
                        </select>           
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                </tr>
                <tr>
                    <td>
                        Fecha Inicial:
                    </td>
                    <td>    
                        <input type='text' class='fechaInicialTab1 fecha' size='10' readonly="readonly" value='{$smarty.now|date_format:"%Y-%m-%d"}'/>
                    </td>
                    <td>&nbsp;</td>
                    <td>&nbsp;</td>
                    <td>    
                        Fecha Final:
                    </td>
                    <td>
                        <input type='text' class='fechaFinalTab1 fecha' size='10' readonly="readonly" value='{$smarty.now|date_format:"%Y-%m-%d"}'/>
                    </td>
                </tr>
            </table>
            <div id='divExport_1' style='float:right;'>
                <a href='javascript:void(0)' onclick='fnExportDoc("pdf",1)'><img src="themes/default/images/pdf_image_inline.gif" title='Exportar a pdf'></a>
                <a href='javascript:void(0)' onclick='fnExportDoc("xlsx",1)'><img src="themes/default/images/xls_image_inline.gif" title='Exportar a xlsx'></a>
            </div>
        </div>
        <div id="divBodyReport1">
            <table width=100% class='list view'>
                <tr class='oddListRowS1'>
                    <th>Campaña</th>
                    <th>Numero campañas</th>
                    <th>SMS</th>
                    <th>Email</th>
                    <th>Fecha</th>
                    <th>tipo campañas</th>
                    <th>campana</th>
                    <th>Ciudad</th>
                </tr>
            
               <tr class='oddListRowS1'>
                    <td>Selecciona los valores de la parte de arriba</td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
             </table>   
        </div>
        <input type='button' id='bttnReport1' onclick="fnBuscaCampanas('Tab1')" value='Buscar' />
    </div>
    <!-- 
       agregado por:darwin rosero 
      se agrega este div para la nueva pestaña  -->
    <div id='divReport2'>
{if $contextMenus}
<script type="text/javascript">
{$contextMenuScript}
{literal}
function lvg_nav(m,id,act,offset,t){
    if(t.href.search(/#/) < 0){return;}
    else{
        if(act=='pte'){
            act='ProjectTemplatesEditView';
        }
        else if(act=='d'){
            act='DetailView';
        }else if( act =='ReportsWizard'){
            act = 'ReportsWizard';
        }else{
            act='EditView';
        }
    {/literal}
        url = 'index.php?module='+m+'&offset=' + offset + '&stamp={$pageData.stamp}&return_module='+m+'&action='+act+'&record='+id;
        t.href=url;
    {literal}
    }
}{/literal}
{literal}
    function lvg_dtails(id){{/literal}
        return SUGAR.util.getAdditionalDetails( '{$pageData.bean.moduleDir|default:$params.module}',id, 'adspan_'+id);{literal}
    }
{/literal}
</script>

    
        <div id="divPreloadReport2" style="color:red;font-family:verdana;"></div>
            
           <!-- {include file='modules/COMM1_communications/tpl/mostrarContactos.tpl'}-->
            
        <div id="divBodyReport2">
        </div>
    </div>
    <div class="windowSearch">
        
    </div>
</div>
<script type='text/javascript' src='{sugar_getjspath file='include/javascript/jquery/grid/js/jquery.ui.datepicker.js'}'></script>
<script type='text/javascript' src='{sugar_getjspath file='include/javascript/jquery/grid/js/jquery.ui.slider.js'}'></script>    
<script type='text/javascript' src='{sugar_getjspath file='include/javascript/jquery/jquery-ui-timepicker-addon.js'}'></script>
<script type='text/javascript' src='{sugar_getjspath file='include/javascript/jquery/i18n/jquery-ui-timepicker-es.js'}'></script>
<link type="text/css" href='{sugar_getjspath file='include/javascript/jquery/jquery-ui-timepicker-addon.css'}' rel="stylesheet" />

<script type='text/javascript' src='{sugar_getjspath file='include/javascript/tinymce.4.1.10/js/tinymce/tinymce.min.js'}'></script>
<script type='text/javascript' src='{sugar_getjspath file='include/javascript/html2canvas/dist/html2canvas.js'}'></script>
<script>
    {literal}
    $(document).ready(function(){
        /**dialogos*/
        $("#divConfigCampania").dialog({
            autoOpen: false,
            modal: true,
            draggable: true,
            resizable:true,
            width:'1000',
            height:'600',
            buttons:{
                "Guardar Cambios":function(){
                    fnGuardarCambios();
                },
                "Cerrar":function(){
                    $(this).dialog('close');
                }
            }
        });
        $("#divHelpDatos").dialog({
            autoOpen: false,
            modal: true,
            draggable: true,
            resizable:true,
            width:'auto',
            buttons:{
                "Cerrar":function(){
                    $(this).dialog('close');
                }
            }
        });

         $('#divHistorialReporteCallcenter').tabs();
        $("#divHistorialReporteCallcenter").dialog({
            autoOpen: false,
            modal: true,
            draggable: true,
            resizable:true,
            width:'1200',
            buttons:{
                "Cerrar":function(){
                    $(this).dialog('close');
                }
            },
            position: 'top'
        });
        
        // set form
        $('#divBodyConfigCampania').html('<form id="frmConfigCampania" enctype="multipart/form-data"  method="post" action="index.php?module=COMM1_communications">'+$('#divBodyConfigCampania').html()+"</form>");
        
        /*tinymce.init({
            selector:'#tarTextoAbiertoEMAIL',
            plugins: [
                "advlist autolink lists link image charmap print preview anchor",
                "searchreplace visualblocks code fullscreen",
                "insertdatetime media table contextmenu paste",
                "openmanager"
            ],
            relative_urls: false,
            remove_script_host: false,
            file_browser_callback: function(field_name, url, type, win) { 
                Quivive(field_name, url, type, win);
                //win.document.getElementById(field_name).value = 'my browser value'; 
            },
            open_manager_upload_path:"../../../../../../../tmpimagenes/",
            theme_advanced_buttons1 : "openmanager",
            toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
            
            // Replace values for the template plugin
            template_replace_values : {
                    username : "Some User",
                    staffid : "991234"
            }
        });*/
        
        /* Se inserto los iconos (abrir ventana y eliminar) para visuaizacion de la ventan*/
        $('#selectLinkTop').after("<a href='javascript:void(0)' onclick='fnShowReportes();'><img src='themes/default/images/ActivitiesReports.gif' title='Reportes'/></a>");

        /* Boton crear en vivo */
        $('#selectLinkTop').after('&nbsp;<input type="button" class="button" value="Crear Envio" onclick="fnShowDialogConfigCampania();"/>');

        $('#delete_listview_top').remove();
        $('#select_actions_disabled_top').remove();
        $('#actionLinkTop').remove();
        $('#delete_listview_bottom').remove();
        $('#select_actions_disabled_bottom').remove();
        $('#actionLinkBottom').remove();
        
        /**datepicker**/
        $.timepicker.regional['es'];
        $('#txtFechaExecute').datetimepicker({
            changeMonth: true,
            numberOfMonths: 1,
            showOn: 'button',
            buttonImage: 'themes/default/images/Calendar.gif',
            buttonImageOnly: true,
            changeYear: true,
            minDate: '0D',
            dateFormat: 'yy-mm-dd',
            timeFormat:  "hh:mm tt",
            controlType: 'select',
            
        }).attr('readonly',true);

        $('#txtFechaHastaReport1').datetimepicker({
            changeMonth: true,
            numberOfMonths: 1,
            showOn: 'button',
            buttonImage: 'themes/default/images/Calendar.gif',
            buttonImageOnly: true,
            changeYear: true,
            minDate: '0D',
            dateFormat: 'yy-mm-dd',
            timeFormat:  "hh:mm tt",
            controlType: 'select',
            
        }).attr('readonly',true);

        $('.ui-datepicker-trigger').click(function(){
            $('.ui-datepicker-current').css('display','none');
        });
        
        // eventos
        $('#selTipoCampania').change(function(){
            fnSelectTipoCampania($(this).val());
            fnCenterDialog();
        });
        $('#tarMsjSMS').keyup(function(){
            return fnCalculaCountChar();
        });
        $('#chkIncluirTextoImagenWHATSAPP').click(function(){
            fnValidaChrTextoInImagenWhatsapp()
        });
        $('#tarMsjWHATSAPP').keyup(function(){
            return fnCalculaCountCharWHATSAPP();
        });
        $('#selTipoEMAIL').change(function(){
            fnVerificarTipoEMAIL($(this).val());
            fnCenterDialog();
        });
        $('#selPlantillaBdEMAIL').change(function(){
            fnPreviewTemplateComm($(this).val()); 
        });
        $('#img1WHATSAPP').change(function(){
            fnValidarExtensionesWhats($(this).val());
        });
        
        var str = "";
            str += "<option value=''></option>";
            str += "<option value='1'>Enero</option>";
            str += "<option value='2'>Febrero</option>";
            str += "<option value='3'>Marzo</option>";
            str += "<option value='4'>Abril</option>";
            str += "<option value='5'>Mayo</option>";
            str += "<option value='6'>Junio</option>";
            str += "<option value='7'>Julio</option>";
            str += "<option value='8'>Agosto</option>";
            str += "<option value='9'>Septiembre</option>";
            str += "<option value='10'>Octubre</option>";
            str += "<option value='11'>Noviembre</option>";
            str += "<option value='12'>Diciembre</option>";
        $('#mes_cumples_basic').html(str);
        
        var strS = "";
            strS += "<option value=''>TODOS</option>";
            strS += "<option value='femenino'>Femenino</option>";
            strS += "<option value='masculino'>Masculino</option>";
        $('#sexo_basic').html(strS);
        
        // clear selects
        $('#mes_cumples_basic').prop('name','mes_cumples_basic');
        $('#sexo_basic').prop('name','sexo_basic');
        
        // set list tiendas
        $('#stu_tiendas_id_name_basic').html($('#selTiendasHidden').html());
        $('#stu_tiendas_id_name_basic').prop('name','stu_tiendas_id_name_basic');
        $('#cliente_vip_c_basic').prop('name','cliente_vip_c_basic');
        $('#cliente_vip_c_basic').html("<option value=''>TODOS LOS CONTACTOS</option><option value='0'>Excluir los VIP</option><option value='1'>Solo los VIP</option>");
        
        $('#last_name_basic').val('{/literal}{$request_custom.last_name_basic}{literal}');
        $('#cedula_nit_basic').val('{/literal}{$request_custom.cedula_nit_basic}{literal}');
        $('#telefono_casa_basic').val('{/literal}{$request_custom.telefono_casa_basic}{literal}');
        $('#telefono_celular_basic').val('{/literal}{$request_custom.telefono_celular_basic}{literal}');
        $('#mes_cumples_basic').val('{/literal}{$request_custom.mes_cumples_basic}{literal}');
        $('#sexo_basic').val('{/literal}{$request_custom.sexo_basic}{literal}');
        $('#ciudad_basic').val('{/literal}{$request_custom.ciudad_basic}{literal}');
        $('#stu_tiendas_id_name_basic').val('{/literal}{$request_custom.stu_tiendas_id_name_basic}{literal}');
        $('#cliente_vip_c_basic').val('{/literal}{$request_custom.cliente_vip_c_basic}{literal}');
        
    });//Fin documento
    
    /**************************************************************************/
    /**************************************************************************/
    /**
     * 
     * Despliega la ventana para los links de los reportes
     */
    function fnShowReportes(){
        $('#divHistorialReporteCallcenter').dialog('open');
        /* Funciones para insertar el contenido en cada uno de los tabs*/
        fnBuscaCampanas('Tab1');
        displayWindow();
    }

    function fnBuscaCampanas(tabNumber){
        $.ajax({
            url: "index.php?module=COMM1_communications",
            type:'POST',
            data: {action:'getReportCampanas',input_type: "JSON", response_type: "JSON",to_pdf:true,fechaInicial:$('.fechaInicial'+tabNumber).val(),fechaFinal:$('.fechaFinal'+tabNumber).val(),selTipoCampana:$('.selTipoCampana'+tabNumber).val()},
            dataType:'json',
            beforeSend:function(){
                //$('#divBodyReport1').html("");
                $('#divExport_1').hide();
                $('#divPreloadReport1').html("<img src='themes/default/images/bar_loader.gif'/><br/>Cargando informaci&oacute;n...");
            },
            success: function(msg){
                console.log(msg.rows);
                $('#divExport_1').show();
                $('#divPreloadReport1').html("");

                if (msg.isValidProcces === true){
                    var str = "<table width=100% class='list view'>";
                        if(msg.rows!=null && msg.rows.length>0){
                            $(msg.rows[0]).each(function(key,value){
                                
                            });
                        }

                        if(msg.rows.length>0){
                            str="";
                            str += "<table width=100% class='list view'>";
                                str += "    <th>    Campaña             </th>";
                                str += "    <th>    Numero campañas     </th>";
                                str += "    <th>    SMS                 </th>";
                                str += "    <th>    Email               </th>";
                                str += "    <th>    Fecha               </th>";
                                str += "    <th>    Tipo campaña        </th>";
                                str += "    <th>    Ciudad              </th>";
                           
                                
                                for(i=0;i<msg.rows.length;i++){
                                str += "<tr class='oddListRowS1'>";
                                str += "    <td>"   + msg.rows[i]['nombreCampana']      +   "</td>";
                                str += "    <td>"   + msg.rows[i]['cantidadCampanas']   +   "</td>";
                                str += "    <td>"   + msg.rows[i]                       +   "</td>";
                                str += "    <td>"   + msg.rows[i]                       +   "</td>";
                                str += "    <td>"   + msg.rows[i]['datetimeExecute']    +   "</td>";
                                str += "    <td>"   + msg.rows[i]['tipoCampana']        +   "</td>";
                                str += "    <td>"   + msg.rows[i]                       +   "</td>";
                                str += "</tr>";
                               }
                              
                                str += "</table>";
                            $('#contenedorGrilla').html(str);
                        }else{
                            str += "<tr><th>NO HAY DATOS PARA MOSTRAR</th></tr>";
                        }
                        str += "</table>";
                        $('#divBodyReport1').html(str);
                }else{
                    alert('Ingresa correctament los valores para realizar la busqueda');
                }
            }
        });
    }

    /*
     * Permite desplegar la ventana informacion para visualizacion de los regitros
     */
    function displayWindow(){
        /*
         * Barra de carga para indicar eperar un momento mientras se carga la informacion
         */
        $('#divReport2').html("<img src='themes/default/images/bar_loader.gif'/><br/>Cargando informaci&oacute;n...");

        /*
         * Load para realizar la carga de la vista y desplegar la grilla con los filtros
         */
        $('#divReport2').load('index.php?module=COMM1_communications&action=displayWindow',function(response, status, xhr){
            
            //alert(status);
            if(status === "error"){
                alert("error al intentar cargar los datos, porfavor intente nuevamente");

            }
            /*
             * Data picker para los campos de fecha en el reporte
             */
            $(".fecha").datepicker({
                buttonImage: "themes/default/images/Calendar.gif",
                buttonImageOnly: true,
                showOn: 'button',
                dateFormat: 'yy-mm-dd',
                changeYear: true,
                changeMonth: true,
                maxDate: '0D',
                minDate: -20
                
            });

            fnInsertarTabla();

            /* Boton para realizar la busqueda de los tados en el controlador*/
            $('.botonRealizarBusqueda').click(function(){
                fnBuscaCampanas('Tab2');
            });
            
        }); //Fin load

        /*
         * Inserta el contenido inicial de la tabla
         */
        function fnInsertarTabla(){
          var str = "<table width=100% class='list view'>";
            str += "<tr class='oddListRowS1'>";
            str += "    <th>    Campaña             </th>";
            str += "    <th>    Numero campañas     </th>";
            str += "    <th>    SMS                 </th>";
            str += "    <th>    Email               </th>";
            str += "    <th>    Fecha               </th>";
            str += "    <th>    Tipo campaña        </th>";
            str += "    <th>    Ciudad              </th>";

            str += "</tr>";
            
            str += "<tr class='oddListRowS1'>";
            str += "    <td>Selecciona los valores de la parte de arriba</td>";
            str += "    <td></td>";
            str += "    <td></td>";
            str += "    <td></td>";
            str += "    <td></td>";
            str += "    <td></td>";
            str += "    <td></td>";
            str += "</tr>";

            str += "</table>";
            $('#contenedorGrilla').html(str);
        }//Fin insertar tabla 
      
    }//Fin funcion displayWindow

    function fnExportDoc(tipo,divnum){
        var _action = null;

        switch(divnum){
            case 1:
                _action = "getReporteComunicaciones";
                break;
        }
    
        $.ajax({
            url: "index.php?module=COMM1_communications",
            type:'POST',
            data: {action:_action,
                    tipo:tipo,
                    input_type: "JSON", 
                    response_type: "JSON",
                    to_pdf:true,
                    numeroLlamadas:$("#fechaInicial").val(),
                    tiendas:$("#fechaInicial").val(),
                    Llamadas:$("#fechaInicial").val(),
                    fecha:$("#fechaInicial").val(),
                    tipoCampana:$("#fechaInicial").val(),
                    ciudad:$("#fechaInicial").val(),
                    tienda : tienda[0],
                    campana: campana,
                    fecha_1 : $("#fechaInicial").val(),
                    fecha_2 : $("#fechaFinal").val()
                 },
            dataType:'json',
            beforeSend:function(){
                $('#divPreloadReport'+divnum).html("<img src='themes/default/images/bar_loader.gif'/><br/>Generando archivo...");
            },
            success: function(msg){
                $('#divPreloadReport'+divnum).html("");
                
                if(msg.archivo_url != null){
                    window.open(msg.archivo_url,'_blank');
                }else{
                    alert("Error en el proceso");
                }
            }
        });
    }

    function fnShowDialogConfigCampania(){
        $('#divConfigCampania').dialog('open');
        // set count chk
            //http://www.etnassoft.com/2010/12/28/cadenas-de-escape-como-poner-tildes-en-javascript/    
          texto1="Hola buen dia sr(a) [first_name], escriba mensaje aqu\u00ED\n\n"
          texto2="STUDIO F \n M\u00F3vil  : (57)xxxxxxxxx - Tel.:(2)xxxxxxx"; 
        $("#tarMsjWHATSAPP").val(texto1+" "+texto2);
        $('#spnCountRowsSend').html($('#selectCountTop').val());
    }
    
    /**
     * 
     * @returns {undefined}
     */
    function fnCenterDialog(){
        $('#divConfigCampania').dialog('widget').position({
            my: "center", at: "center", of: window
        });
    }
    

    function fnSelectTipoCampania(tipo){
        $('#divEmail').hide();
        $('#divSms').hide();
        $('#divWhatsapp').hide();
        switch(tipo){
            case "EMAIL":
                $('#divEmail').show();
                break;
            case "SMS":
                $('#divSms').show();
                break;
            case "WHATSAPP":
                $('#divWhatsapp').show();
                break;
        }
    }
    

    function fnCalculaCountChar(){
        // obetnemos la cant d char del tar
        var cantCh = $('#tarMsjSMS').val().length;
        $('#spnCountCaractSMS').html(cantCh+"/160");
        if(cantCh >= 160){
            $('#tarMsjSMS').val($('#tarMsjSMS').val().substring(0,160));
            $('#spnCountCaractSMS').html($('#tarMsjSMS').val().length+"/160");
            return false;
        }
        return true;
    }
    
    /**
     * 
     * @returns {undefined}
     */
    function fnGuardarCambios(){
        // validamos datos
        if(!fnValidateDatosFormPrincipal()){
            return;
        }
        // recojemos los ids marcados de los contacts
        var arrids = [];
        if($('#massall_top').is(':checked')){
            arrids = true;
        }else{
            for(var i=0;true;i++){
                if(!document.getElementById('chkrowtpl-'+i)){
                    break;
                }
                if($('#chkrowtpl-'+i).is(':checked')){
                    arrids.push($('#chkrowtpl-'+i).val());
                }
            }
        }
        // validamos si existen campos para cruzar con columnas
        var txtC = fnValidateCamposCruzar();
        $('#hdnBolCamposCruzar').val('false');
        if(txtC != null){
            if(!confirm(
                "El sistema detecto que en el texto a enviar existen los textos siguientes:\n"+
                txtC+
                "\n\n"+
                "Comfirma que esta usando estos textos con el proposito de que se reemplacen con los datos del contacto?"
            )
            ){
                return;
            }else{
                $('#hdnBolCamposCruzar').val('true');
            }
        }
        // set ids values
        $('#hdnidscontacts').val(arrids);
        // enviamos los datos al servidor
        if(confirm("Realmente desea crear esta campa\u00f1a?")){
            $(".ui-dialog-buttonpane button:contains('Guardar Cambios')").button("disable");
            $('#frmConfigCampania').submit();
        }
    }
    
    /**
     * 
     * @returns {Boolean}
     */
    function fnValidateDatosFormPrincipal(){
        if($('#spnCountRowsSend').html()=='0'){
            alert("Debe seleccionar minimo un registro, proceso abortado");
            return false;
        }
        if($('#txtNombreCampania').val() == ''){
            alert("Debe ingresar el nombre de la campa\u00f1a, proceso abortado");
            return false;
        }
        if($('#selTipoCampania').val() == ''){
            alert("Debe seleccionar el tipo de mensaje a enviar, proceso abortado");
            return false;
        }
        if($('#txtFechaExecute').val() == ''){
            alert("Debe seleccionar la fecha y hora de envio, proceso abortado");
            return false;
        }
        // validamos q la hora sea mayor a la hora actual
        var f=new Date();
        var anio = f.getFullYear();
        var mes = (f.getMonth()+1);
            mes = (mes<10?'0'+mes:mes);
        var dia = (f.getDate());
            dia = (dia<10?'0'+dia:dia);
        var cadfull = anio+mes+dia;
        var cadnow = cadfull+(f.getHours()<10?'0'+f.getHours():f.getHours().toString())+':'+(f.getMinutes()<10?'0'+f.getMinutes():f.getMinutes().toString());
        cadnow = cadnow.replace(/:/gi, "");
        // sacamos el vr del date input
        var tmz =  $('#txtFechaExecute').val().substring($('#txtFechaExecute').val().length,$('#txtFechaExecute').val().length-4);
        var houtC =  $('#txtFechaExecute').val().substring($('#txtFechaExecute').val().length-10,$('#txtFechaExecute').val().length);
        var arrHC = houtC.split(":");
        
        //console.log(arrHC);
        //console.log(tmz);
        var Hfinal = "";
        if(parseInt(arrHC[0])==12 && tmz== 'a.m.'){
            // cambiamos la hora a 00
            Hfinal = "00:"+arrHC[1]+tmz;
        }else{
            if(parseInt(arrHC[0])>=1 && parseInt(arrHC[0]) <= 11){
                if(tmz == 'p.m.'){
                    // ponemos la hora militar
                    var hff = (parseInt(arrHC[0]) + 12);
                }else{
                    var hff = arrHC[0];
                }
                Hfinal = hff+":"+arrHC[1];
            }
        }
        var cadinput = $('#txtFechaExecute').val().substring(0,$('#txtFechaExecute').val().length-10);
        cadinput = (cadinput + Hfinal);
        cadinput = cadinput.substring(0,cadinput.length-4);
        //console.log(cadinput);
        cadinput = cadinput.replace(/-/gi, "");
        cadinput = cadinput.replace(/ /gi, "");
        cadinput = cadinput.replace(/:/gi, "");
        //cadinput = cadinput.replace(/:/gi, "");
        console.log((cadnow)+'--->'+(cadinput));
        if(parseInt(cadnow) > parseInt(cadinput)){
            alert("La hora seleccionada debe ser mayor a la hora actual, proceso abortado");
            return false;
        }
        
        // validamos datos de tipo tpl
        switch($('#selTipoCampania').val()){
            case "EMAIL":
                // verificamos el tipo de email
                if($('#selTipoEMAIL').val() == 'PLANTILLA'){
                    // validamos q se halla seleccionado al menos un plantilla creada
                    if($('#selPlantillaBdEMAIL').val()==''){
                        alert("Debe seleccionar al menos una plantilla, proceso abortado");
                        return false;
                    }
                }else{
                    if($('#selTipoEMAIL').val() == 'ABIERTO'){
                        // validamos q se halla ingresado algun texto en el editpr d html
                        if(tinymce.get('tarTextoAbiertoEMAIL').getContent() == ""){
                            alert("Debe ingresar un texto valido en el editor de texto, proceso abortado");
                            return false;
                        }
                    }
                }
                break;
            case "SMS":
                // validamos el text area de sms
                if($('#tarMsjSMS').val() == ''){
                    alert("Debe ingresar el texto del SMS, proceso abortado");
                    return false;
                }
                // validamos la cantidad de texto del sms
                var cantCh = $('#tarMsjSMS').val().length;
                if(cantCh > 160){
                    alert("La cantidad de caracteres del cuadro de texto del SMS es mayor a 160, proceso abortado");
                    $('#tarMsjSMS').val($('#tarMsjSMS').val().substring(0,160));
                    return false;
                }
                break;
            case "WHATSAPP":
                // validamos que al menos se halla ingresado un texto o imagen
                if($('#tarMsjWHATSAPP').val() == '' && $('#img1WHATSAPP').val() == ''){
                    alert('Debe ingresar el texto del mensaje o seleccionar una imagen o tambien puede seleccionar una imagen e ingresar un texto a enviar, proceso abortado');
                    return false;
                }
                break;
        }
        return true;
    }
    
    /***************************************************************************/
    /***************************************************************************/
    

    function fnValidaChrTextoInImagenWhatsapp(){
        $('#spnCountCaractWHATSAPP').hide();
        if($('#chkIncluirTextoImagenWHATSAPP').is(':checked')){
            $('#spnCountCaractWHATSAPP').show();
        }
        // validamos q la cantidad d chr ingresado sea menor o igual a 160
        var cantCh = $('#tarMsjWHATSAPP').val().length;
        if(cantCh > 160){
            alert('El limite del texto a incluir en la imagenes de whatsapp es de 160 caracteres');
            fnCalculaCountCharWHATSAPP();
            return false;
        }
    }
    
 
    function fnCalculaCountCharWHATSAPP(){
        // obetnemos la cant d char del tar
        var cantCh = $('#tarMsjWHATSAPP').val().length;
        $('#spnCountCaractWHATSAPP').html(cantCh+"/160");
        
        // validamos si esta chekeado
        if($('#chkIncluirTextoImagenWHATSAPP').is(':checked')){
            if(cantCh >= 160){
                $('#tarMsjWHATSAPP').val($('#tarMsjWHATSAPP').val().substring(0,160));
                $('#spnCountCaractWHATSAPP').html($('#tarMsjWHATSAPP').val().length+"/160");
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 
     * @param {type} value
     * @returns {Boolean}
     */
    function fnValidarExtensionesWhats(value){
        var ext = value.substring(value.lastIndexOf(".")+1);
        if(
            ext != "png" && ext != "jpg" && ext != "bmp" && ext != "gif" && ext != "jpeg" &&
            ext != "PNG" && ext != "JPG" && ext != "BMP" && ext != "GIF" && ext != "JPEG"
        ){
            alert("las extensiones permitidas son: .jpg, .png, .gif, .bmp");
            $('#img1WHATSAPP').val("");
            return false;
        }
    }
    
    /**
     * consulta el html del template d bd
     * 
     * @param {type} idtpl
     * @returns {undefined}
     */
    function fnPreviewTemplateComm(idtpl){
        $('#divPreviewTemplateEMAIL').html("");
        if(idtpl == ""){
            return;
        }
        // consultamos via ajax el html de la plantilla
        $.ajax({
            url: "index.php?module=COMM1_communications",
            type:'POST',
            data: {action:'getHtmlTemplate',input_type: "JSON", response_type: "JSON",idtpl:idtpl,to_pdf:true},
            dataType:'json',
            beforeSend:function(){
                $('#imgAnimTpl').remove();
                $('#selPlantillaBdEMAIL').after("<img id='imgAnimTpl' src='themes/default/images/ui-anim_basic_16x16.gif' />");
            },
            success: function(msg){
                $('#imgAnimTpl').remove();
                if(msg!=null && msg.rows!=null){
                    var strHtml = "";
                    // set los 5 posibles textos
                    if(msg.rows[0].text1 != null){
                        strHtml += msg.rows[0].text1;
                    }
                    if(msg.rows[0].text2 != null){
                        strHtml += msg.rows[0].text2;
                    }
                    if(msg.rows[0].text3 != null){
                        strHtml += msg.rows[0].text3;
                    }
                    if(msg.rows[0].text4 != null){
                        strHtml += msg.rows[0].text4;
                    }
                    if(msg.rows[0].text5 != null){
                        strHtml += msg.rows[0].text5;
                    }
                    putImageCanvas(strHtml);
                }else{
                    alert("Error al consultar el tpl seleccionado");
                }
            }
        });
    }
    
    /**
     * 
     * @param {type} strHtml
     * @returns {undefined}
     */
    function putImageCanvas(strHtml){
        var pE = document.createElement("div");
        pE.setAttribute("id",'pIdTmp');
        pE.setAttribute("style",'width:auto;height:auto;');
        pE.innerHTML = html_entity_decode(strHtml);
        console.log(html_entity_decode(strHtml));
        //pE.appendChild(node);
        $('#pIdTmp').remove();
        $('body').append(pE);
        
        html2canvas(pE,{
            allowTaint: true,
            logging: true,
            onrendered:function(canvas) {
                var canvas_n = document.createElement("canvas");
                canvas_n.width = 900;
                canvas_n.height = canvas.height;
                var ctx = canvas_n.getContext('2d');
                
                
                ctx.imageSmoothingEnabled = false;
                ctx.webkitImageSmoothingEnabled = false;
                ctx.mozImageSmoothingEnabled = false;
                try {
                    ctx.drawImage(canvas, 0, 0, 900,canvas.height);
                }
                catch(err) {
                    console.log(err);
                }
                $('#divPreviewTemplateEMAIL').html(canvas_n);
                $('#pIdTmp').remove();
            }
        });
        
    }
    
    function html_entity_decode(string, quote_style) {
        var hash_map = {},
          symbol = '',
          tmp_str = '',
          entity = '';
        tmp_str = string.toString();

        if (false === (hash_map = get_html_translation_table('HTML_ENTITIES', quote_style))) {
          return false;
        }

        // fix &amp; problem
        // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
        delete(hash_map['&']);
        hash_map['&'] = '&amp;';

        for (symbol in hash_map) {
          entity = hash_map[symbol];
          tmp_str = tmp_str.split(entity)
            .join(symbol);
        }
        tmp_str = tmp_str.split('&#039;')
          .join("'");

        return tmp_str;
    }
    
    function get_html_translation_table(table, quote_style){
        var entities = {},
          hash_map = {},
          decimal;
        var constMappingTable = {},
          constMappingQuoteStyle = {};
        var useTable = {},
          useQuoteStyle = {};

        // Translate arguments
        constMappingTable[0] = 'HTML_SPECIALCHARS';
        constMappingTable[1] = 'HTML_ENTITIES';
        constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
        constMappingQuoteStyle[2] = 'ENT_COMPAT';
        constMappingQuoteStyle[3] = 'ENT_QUOTES';

        useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
        useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() :
          'ENT_COMPAT';

        if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
          throw new Error('Table: ' + useTable + ' not supported');
          // return false;
        }

        entities['38'] = '&amp;';
        if (useTable === 'HTML_ENTITIES') {
          entities['160'] = '&nbsp;';
          entities['161'] = '&iexcl;';
          entities['162'] = '&cent;';
          entities['163'] = '&pound;';
          entities['164'] = '&curren;';
          entities['165'] = '&yen;';
          entities['166'] = '&brvbar;';
          entities['167'] = '&sect;';
          entities['168'] = '&uml;';
          entities['169'] = '&copy;';
          entities['170'] = '&ordf;';
          entities['171'] = '&laquo;';
          entities['172'] = '&not;';
          entities['173'] = '&shy;';
          entities['174'] = '&reg;';
          entities['175'] = '&macr;';
          entities['176'] = '&deg;';
          entities['177'] = '&plusmn;';
          entities['178'] = '&sup2;';
          entities['179'] = '&sup3;';
          entities['180'] = '&acute;';
          entities['181'] = '&micro;';
          entities['182'] = '&para;';
          entities['183'] = '&middot;';
          entities['184'] = '&cedil;';
          entities['185'] = '&sup1;';
          entities['186'] = '&ordm;';
          entities['187'] = '&raquo;';
          entities['188'] = '&frac14;';
          entities['189'] = '&frac12;';
          entities['190'] = '&frac34;';
          entities['191'] = '&iquest;';
          entities['192'] = '&Agrave;';
          entities['193'] = '&Aacute;';
          entities['194'] = '&Acirc;';
          entities['195'] = '&Atilde;';
          entities['196'] = '&Auml;';
          entities['197'] = '&Aring;';
          entities['198'] = '&AElig;';
          entities['199'] = '&Ccedil;';
          entities['200'] = '&Egrave;';
          entities['201'] = '&Eacute;';
          entities['202'] = '&Ecirc;';
          entities['203'] = '&Euml;';
          entities['204'] = '&Igrave;';
          entities['205'] = '&Iacute;';
          entities['206'] = '&Icirc;';
          entities['207'] = '&Iuml;';
          entities['208'] = '&ETH;';
          entities['209'] = '&Ntilde;';
          entities['210'] = '&Ograve;';
          entities['211'] = '&Oacute;';
          entities['212'] = '&Ocirc;';
          entities['213'] = '&Otilde;';
          entities['214'] = '&Ouml;';
          entities['215'] = '&times;';
          entities['216'] = '&Oslash;';
          entities['217'] = '&Ugrave;';
          entities['218'] = '&Uacute;';
          entities['219'] = '&Ucirc;';
          entities['220'] = '&Uuml;';
          entities['221'] = '&Yacute;';
          entities['222'] = '&THORN;';
          entities['223'] = '&szlig;';
          entities['224'] = '&agrave;';
          entities['225'] = '&aacute;';
          entities['226'] = '&acirc;';
          entities['227'] = '&atilde;';
          entities['228'] = '&auml;';
          entities['229'] = '&aring;';
          entities['230'] = '&aelig;';
          entities['231'] = '&ccedil;';
          entities['232'] = '&egrave;';
          entities['233'] = '&eacute;';
          entities['234'] = '&ecirc;';
          entities['235'] = '&euml;';
          entities['236'] = '&igrave;';
          entities['237'] = '&iacute;';
          entities['238'] = '&icirc;';
          entities['239'] = '&iuml;';
          entities['240'] = '&eth;';
          entities['241'] = '&ntilde;';
          entities['242'] = '&ograve;';
          entities['243'] = '&oacute;';
          entities['244'] = '&ocirc;';
          entities['245'] = '&otilde;';
          entities['246'] = '&ouml;';
          entities['247'] = '&divide;';
          entities['248'] = '&oslash;';
          entities['249'] = '&ugrave;';
          entities['250'] = '&uacute;';
          entities['251'] = '&ucirc;';
          entities['252'] = '&uuml;';
          entities['253'] = '&yacute;';
          entities['254'] = '&thorn;';
          entities['255'] = '&yuml;';
        }

        if (useQuoteStyle !== 'ENT_NOQUOTES') {
          entities['34'] = '&quot;';
        }
        if (useQuoteStyle === 'ENT_QUOTES') {
          entities['39'] = '&#39;';
        }
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';

        // ascii decimals to real symbols
        for (decimal in entities) {
          if (entities.hasOwnProperty(decimal)) {
            hash_map[String.fromCharCode(decimal)] = entities[decimal];
          }
        }

        return hash_map;
    }
    
    /***************************************************************************/
    /**************************************************************************/
    
    /**
     * 
     * @param {type} value
     * @returns {undefined}
     */
    function fnVerificarTipoEMAIL(value){
        $('#divTemplatesEMAIL').hide();
        $('#divAbiertoEMAIL').hide();
        if(value == "PLANTILLA"){
            $('#divTemplatesEMAIL').show();
        }else{
            if(value == "ABIERTO"){
                $('#divAbiertoEMAIL').show();
            }
        }
    }
    
    /**
     * 
     * @param {type} field_name
     * @param {type} url
     * @param {type} type
     * @param {type} win
     * @returns {undefined}
     */
    function Quivive(field_name, url, type, win) {
        var file = "";
        if(navigator.appName.indexOf('Microsoft')!=-1)
            file = modalDialogShow('studioenero19/include/javascript/tinymce.4.1.10/js/tinymce/plugins/openmanager/index.php?d=../../../../../../../tmpimagenes/&filemanager=mce',1024,600);
        else
            win.open('../../../../studioenero19/include/javascript/tinymce.4.1.10/js/tinymce/plugins/openmanager/index.php?d=../../../../../../../tmpimagenes/&filemanager=mce4&mod='+field_name, 'ImageBrowser', 'width=1024,height=600,scrollbars=no,status=yes,location=no,resizable=yes,dependent');
        if(file > "") {
            document.getElementById(field_name).value = file;
            win.ImageDialog.getImageData(file);
        }
    }
    
    /**
     * muestra el dialog
     * 
     * @param {type} url
     * @param {type} width
     * @param {type} height
     * @returns {Number}
     */
    function modalDialogShow(url,width,height) {
        var input = window.showModalDialog(url,window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;scroll:no;edge:Raised;center:Yes;help:No;Resizable:yes;Maximize:yes");
        return input;
    }
    
    /**
     * 
     * @param {type} obj
     * @returns {undefined}
     */
    function fnchkDesChkAll(obj){
        if(!$(obj).is(':checked')){
            $('#massall_top').prop('checked',false);
            $('#massall_bottom').prop('checked',false);
        }
    }
    
   
    function fnValidateCamposCruzar(){
        // verificamos el tipo y sacamos el html
        var txtE = "";
        // validamos datos de tipo tpl
        switch($('#selTipoCampania').val()){
            case "EMAIL":
                // verificamos el tipo de email
                if($('#selTipoEMAIL').val() == 'PLANTILLA'){
                    txtE = $('#divPreviewTemplateEMAIL').html();
                }else{
                    if($('#selTipoEMAIL').val() == 'ABIERTO'){
                        txtE = tinymce.get('tarTextoAbiertoEMAIL').getContent();
                    }
                }
                break;
            case "SMS":
                txtE = $('#tarMsjSMS').val();
                break;
            case "WHATSAPP":
                txtE = $('#tarMsjWHATSAPP').val();
                break;
        }
        // buscamos los string
        var str = "";
        var n = -1;
        console.log(txtE);
        n = txtE.indexOf("[first_name]");
        console.log(n);
        if(n != -1){
            str += "[first_name]\n";
        }
        n = txtE.indexOf("[last_name]");
        console.log(n);
        if(n != -1){
            str += "[last_name]\n";
        }
        n = txtE.indexOf("[phone_mobile]");
        if(n != -1){
            str += "[phone_mobile]\n";
        }
        n = txtE.indexOf("[cedula_nit_c]");
        if(n != -1){
            str += "[cedula_nit_c]\n";
        }
        return (str==""?null:str);
    }
    
    function fnShowHelpDatos(){
        $('#divHelpDatos').dialog('open');
    }
    
    function fnRedirectEditarTemplate(){
        var recordtemplate = $('#selPlantillaBdEMAIL').val();
        if(recordtemplate == "" || recordtemplate==undefined){
            return;
        }
        var url = document.location.href;
        var arrUrl = url.split("?");
        var urlFinal = arrUrl[0]+"?module=COMM1_templates_communications&action=EditView&record="+recordtemplate;
        location.href = urlFinal;
    }
    
    {/literal}
</script>
