<?php
if ($from_view == null) {
    echo'</br>';
    echo TbHtml::button(Yii::t('default', 'Add'), array(
	'style' => TbHtml::BUTTON_COLOR_SUCCESS,
	'size' => TbHtml::BUTTON_SIZE_DEFAULT,
	'data-toggle' => 'modal',
	'data-target' => '#document-form',
	'id' => 'add_document'
    ));
}
?>
&nbsp;
<?php
echo TbHtml::button(Yii::t('default', 'Uploaded Documents Checklist'), array(
    'style' => TbHtml::BUTTON_COLOR_SUCCESS,
    'size' => TbHtml::BUTTON_SIZE_DEFAULT,
    'data-toggle' => 'modal',
    'data-target' => '#checklist-form',
    'id' => 'check_list_modal_document',
    'onClick' => 'checkSelectedOptions()'
));
echo'</br>';
?>
<div id="flash-msg-document">
    <br>
    <?php $this->widget('bootstrap.widgets.TbAlert'); ?>
</div>
<?php
//----------------------------------------------------------------

    $this->widget('yiiwheels.widgets.grid.WhGridView', array(
	'id' => 'document-grid',
	'ajaxUrl' => Yii::app()->createUrl('document/update'),
	'headerOffset' => 40,
	'responsiveTable' => true,
	'dataProvider' => $dataProvider,
	'columns' => array(
	    array(
		'type' => 'raw',
		'name' => 'name',
		'value' => '$data["path"] == "" ? CHtml::link($data["name"], array("/document/download", "id" => $data["id"],"path"=>$data["path"]),array("target"=>"_blank"))
					    : CHtml::link( substr($data["name"],0,strrpos($data["name"], "-")).substr($data["name"],strrpos($data["name"], "."),  strlen($data["name"])), array("/document/download", "id" => $data["id"],"path"=>$data["path"]),array("target"=>"_blank")) ',
		'header' => yii::t('default', 'Document Name'),
	    ),
	    array(
		'name' => 'date',
		'header' => yii::t('default', 'Upload Date'),
	    ),
	    array(
		'class' => 'CButtonColumn',
		'htmlOptions' => array('width' => '100'),
		'template' => ($from_view == null) ? '{delete}' : '',
		'afterDelete' => 'function(link,success,data){ if(success) $("#flash-msg").html(data); }',
		'buttons' => array(
		    'delete' => array(
			'label' => Yii::t('default', 'Delete'),
			'url' => '"#"',
			'click' => 'function(){
                             var rowIndex = $(this).closest("tr").index();
                             var rowId = $("#"+$(this).closest("div.grid-view").attr("id")+" > div.keys > span:eq("+rowIndex+")").text();
                             delete_row_and_update_document_grid(rowId);
                             return false;}',
		    ),
		    'download' => array(
			'label' => Yii::t('default', 'Download'),
			'url' => '"#"',
			'click' => 'function(){
                             var rowIndex = $(this).closest("tr").index();
                             var rowId = $("#"+$(this).closest("div.grid-view").attr("id")+" > div.keys > span:eq("+rowIndex+")").text();			    
                             download_document(rowId);
                             return false;}',
			'imageUrl' => Yii::app()->request->baseUrl . '/css/flags/download.png',
		    ),
	    ))
	),
    ));
    Yii::app()->controller->renderPartial('/document/_check_list_modal', array('model_id' => $model_id, 'from_view' => $from_view));
    Yii::app()->controller->renderPartial('/document/_modal', array('model_id' => $model_id, 'from_view' => $from_view));
?>

    <script type="text/javascript">

        $('.close').click(function() {
    	$('#checklist-form').removeClass('in');
        });

        $('#cancel_btn').click(function() {
    	$('#checklist-form').removeClass('in');
        });
        function save_changes_and_update_document_grid() {

    	var document_name = $("#document_name").val();
    	var document_date = '';
    	var document_path = $("#path_of_file").val();
    	var document_file_type = $("#file_type").val();
    	var document_file_size = $("#file_size").val();
    	var document_type_ids = "";

    	if (document_path == "") {
    	    alert('<?php echo Yii::t('default', 'You need to upload a file'); ?>');
    	    return;
    	}

    	document_id++;
    	var elem = {'id': document_id, 'name': document_name, 'date': document_date, 'path': document_path, 'file_type': document_file_type, "file_size": document_file_size};
    	document_array[document_id] = elem;

    	$.fn.yiiGridView.update('document-grid', {
    	    data: {"data": JSON.stringify(document_array) + '##' + tid_id}
    	});
    	$("#document_hidden_input").val(JSON.stringify(document_array));
    	$("#check_list_modal_document").show();
    	//empty the modal inputs after hiding it
    	$("#document_name").val("");
    	$("#document_date").val("");
    	$("#path_of_file").val("");
    	$("#file_type").val("");
    	$("#file_size").val("");
    	$("#upload_file").val("");
    	$(".qq-upload-file").html("");
    	$(".qq-upload-list").html("");


    	$("#checklist-form").addClass("in");
    	setTimeout($("#checklist-form").show(), 5000);



        }

        function save_changes_and_update_document_types() {


    	var document_type_ids = "";


    	$(':input', '#checklist_div').each(function() {
    	    var type = this.type;
    	    if (type == 'checkbox')
    		if ($(this).attr('checked') == 'checked')
    		    document_type_ids += ($(this).attr('value')) + ',';
    	});

    	$("#document_type_ids_input").val(document_type_ids);

    	$.ajax({
    	    type: 'POST',
    	    data: {
    		'docType': document_type_ids,
    		'tid_id': tid_id
    	    },
    	    url: '<?php echo Yii::app()->createAbsoluteUrl("document/updateDocTyps"); ?>',
    	    success: function(data) {
    		$("#checklist_div").html('');
    		$("#checklist_div").html(data);
    		$("#checklist-form").removeClass("in");

    	    },
    	    error: function(data) { // if error occured

    	    }
    	});

        }

        function checkSelectedOptions(){
    	$(':input', '#checklist_div').each(function() {
    	    var type = this.type;
    	    var value = $("#document_type_ids_input").val();
    	    if (type == 'checkbox' && value != '' && value != null)
    		if ($(this).attr('checked') == 'checked' && value.indexOf($(this).attr('value')) == -1)
    		    $(this).attr('checked',false);
    	});
        }


        //----------------------------------------------------------
        function delete_row_and_update_document_grid(id) {
    	var message = '<?php echo YII::t('zii', 'Are you sure you want to delete this item?'); ?>';
    	if (!confirm(message)) {
    	    return;
    	}
    	$.each(document_array, function(key, value) {
    	    if (value) {
    		if (document_array[key].id == id) {
    		    delete document_array[key];
    		}
    	    }
    	});
    	$.fn.yiiGridView.update('document-grid', {
    	    data: {"data": JSON.stringify(document_array) + '##' + tid_id}

    	});
    	$("#document_hidden_input").val(JSON.stringify(document_array));
        }


        var document_url = "<?php echo Yii::app()->createAbsoluteUrl("/document/download"); ?>";


        function download_document(id) {

    	var path = '';
    	$.each(document_array, function(key, value) {
    	    if (value) {
    		if (document_array[key].id == id) {
    		    path = document_array[key].path;
    		}
    	    }
    	});

    	var url = addParam(document_url, "id", id);

    	//window.location.href = addParam(url,"path",path);

        }

        $(document).ready(function() {
    	var from_view = '<?php echo $from_view; ?>';
	if (from_view != '') {
	    $(':input', '#checklist_div').each(function() {
		var type = this.type;
		if (type == 'checkbox')
		    $(this).attr('disabled', 'disabled');

	    });
	}
	if (document_array.length == 0){
	    var value = document_type_ids_value;
	    if(value == null || value == '')
		$("#check_list_modal_document").hide();
	}
    });

</script>