var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
function FormatNumber(number, precision) {
	var precision = precision || 2;
	// make string..
	number = number + '';
	number = number.replace(',', '.');
	// round
	number = toFixed(number, precision);
	// add 1000 sep
	var tmp = number.split(".");
	var c = '';
	for (var i = tmp[0].length; i != -1; i--) {
		c += tmp[0].charAt(i);
		if ((tmp[0].length - i) == 0 || i == 0)
			continue;
		if ((tmp[0].length - i) % 3 == 0)
			c += '.';
	}
	// reverse c
	c = c.split("").reverse().join("");

	return c + ',' + tmp[1];
}

function UnformatNumber(number) {
	// make string..
	number = number + '';
	// remove 1000 sep
	number = number.replace('.', '');
	// change ',' to '.'
	number = number.replace(',', '.');

	return parseFloat(number);
}

// round with precision
function toFixed(value, precision) {
	var precision = precision || 0, neg = value < 0, power = Math.pow(10,
			precision), value = Math.round(value * power), integral = String((neg ? Math.ceil
			: Math.floor)(value / power)), fraction = String((neg ? -value
			: value)
			% power), padding = new Array(Math.max(precision - fraction.length,
			0) + 1).join('0');

	return precision ? integral + '.' + padding + fraction : integral;
}

function InitializeInterestTable(){
	   // Initialize appendGrid
    $('#tblAppendGrid').appendGrid({
        hideRowNumColumn: true,
        initRows: 1,
        // definicje kolumn
        columns: [
            { name: 'date_from', display: 'Od', type: 'custom', value: '',
                    customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                        // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Create a span as a container
                        var ctrl = document.createElement('span');
                        // Set the ID and name to container and append it to parent control which is a table cell
                        $(ctrl).attr({ id: ctrlId, name: ctrlId }).appendTo(parent);
                        // Create extra controls and add to container
                        $('<div style="text-align: right;vertical-align: text-top;">').appendTo(ctrl);
                        $('<input>', { type: 'text', maxLength: 10, id: ctrlId + '_date',name: ctrlId + '_date',style: 'width:100px;text-align:right;float:right;', class: 'inputs'}).appendTo(ctrl);
                        $('<img border="0" id="'+ctrlId + '_tigger'+'" align="absmiddle" alt="Wprowadź datę" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></div>').appendTo(ctrl);
                        $('<script type="text/javascript">Calendar.setup ({inputField : "'+ctrlId + '_date'+'",daFormat : "%d.%m.%Y %H:%M",button : "'+ctrlId + '_tigger'+'",singleClick : true,dateStr : "",step : 1,weekNumbers:false});</script>').appendTo(ctrl);
       
                        // Finally, return the container control
                        return ctrl;
                    },
                    customGetter: function (idPrefix, name, uniqueIndex) {
                    	// Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Check the input value and split it to array if valid
                
                        // Set the value to different spinners
                       return $('#' + ctrlId + '_date').val();
                    
                    },
                    customSetter: function (idPrefix, name, uniqueIndex, value) {
                        // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Check the input value and split it to array if valid
              
                        // Set the value to different spinners
                       $('#' + ctrlId + '_date').val(value);
                    }
                },
                { name: 'date_to', display: 'Do', type: 'custom', value: '',
                    customBuilder: function (parent, idPrefix, name, uniqueIndex) {
                        // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Create a span as a container
                        var ctrl = document.createElement('span');
                        // Set the ID and name to container and append it to parent control which is a table cell
                        $(ctrl).attr({ id: ctrlId, name: ctrlId }).appendTo(parent);
                        // Create extra controls and add to container
                        $('<div style="text-align: right;vertical-align: text-top;">').appendTo(ctrl);
                        $('<input>', { type: 'text', maxLength: 10, id: ctrlId + '_date',name: ctrlId + '_date',style: 'width:100px;text-align:right;float:right', class: 'inputs'}).appendTo(ctrl);
                        $('<img border="0" id="'+ctrlId + '_tigger'+'" align="absmiddle" alt="Wprowadź datę" src="themes/Sugar5/images/jscalendar.gif?s=bed8cd35065048ceebdc639ebe305e2c&c=1"></div>').appendTo(ctrl);
                        $('<script type="text/javascript">Calendar.setup ({inputField : "'+ctrlId + '_date'+'",daFormat : "%d.%m.%Y %H:%M",button : "'+ctrlId + '_tigger'+'",singleClick : true,dateStr : "",step : 1,weekNumbers:false});</script>').appendTo(ctrl);
        
                        // Finally, return the container control
                        return ctrl;
                    },
                    customGetter: function (idPrefix, name, uniqueIndex) {
                    	// Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Check the input value and split it to array if valid
                
                        // Set the value to different spinners
                       return $('#' + ctrlId + '_date').val();
                    
                    },
                    customSetter: function (idPrefix, name, uniqueIndex, value) {
                        // Prepare the control ID/name by using idPrefix, column name and uniqueIndex
                        var ctrlId = idPrefix + '_' + name + '_' + uniqueIndex;
                        // Check the input value and split it to array if valid
              
                        // Set the value to different spinners
                       $('#' + ctrlId + '_date').val(value);
                    }
                },
            {name: 'rate', display: '%', type: 'text', ctrlAttr: {maxlength: 100}, ctrlCss: {width: '100%','text-align': 'right'}, ctrlClass: 'inputs',
            	onChange: function (evt, rowIndex) {
            	// liczenie vatu
                    var data = $('#tblAppendGrid').appendGrid('getRowValue', rowIndex);
                    if (data.rate!='') {
                        // wtrzykwianie danych
                        $('#tblAppendGrid').appendGrid('setCtrlValue', 'rate', rowIndex, FormatNumber(data.rate));
                    }
                }, 
                onClick: function (evt, rowIndex) {
                	// zaznacznie wybranego pola
                	 var elem = $('#tblAppendGrid').appendGrid('getCellCtrl', 'rate', rowIndex);
                    $(elem).select();
                }},
            {name: 'symbol', display: 'Symbol',type: 'select', ctrlOptions: { 0: '{Wybierz}', M: 'M', R: 'R', D: 'D'} ,ctrlAttr: {maxlength: 100}, ctrlCss: {width: '100%','text-align': 'right'}, ctrlClass: 'inputs'},
            {name: 'id', display: 'ID', invisible: true}

        ],
        // custome guziczki
        customGridButtons: {
            insert: $('<img>').css('color', 'red').text('Insert').get(0),
            // Use a function that create DOM element
            moveUp: function (){
                var button = document.createElement('img');
                button.src = 'modules/EcmQuotes/images/moverowup.gif';
                return button;
            },
            moveDown: function (){
                var button = document.createElement('img');
                button.src = 'modules/EcmQuotes/images/moverowdown.gif';
                return button;
            },
            removeLast: function (){
                var button = document.createElement('img');
                button.src = 'modules/EcmQuotes/images/deleterow.gif';
                return button;
            },
            append: function (){
                var button = document.createElement('img'); 
                button.src = 'modules/EcmQuotes/images/insertrow.gif';
                return button;
            }
        },
        afterRowAppended: function (caller, parentRowIndex, addedRowIndex) {
            $('thead').removeClass('ui-widget-header');
            $('td').removeClass('ui-widget-header');
            $('tbody').removeClass('ui-widget-content');
            $('td').removeClass('ui-widget-content');
            $('tfoot').removeClass('ui-widget-header');
            var data = $('#tblAppendGrid').appendGrid('getRowValue', parentRowIndex);
            if(data){
	            var date_to=data.date_to;
	            date_to = new Date(date_to.replace(pattern,'$3-$2-$1'));
	            var date_from=data.date_from;
	            date_from = new Date(date_from.replace(pattern,'$3-$2-$1'));
	            if(data.date_to!='' && data.date_from!='' && date_to>date_from && data.rate && data.symbol!=0){
	            	 var uq = $('#tblAppendGrid').appendGrid('getUniqueIndex', parentRowIndex);
	            	 $('#tblAppendGrid_date_from_'+uq+'_tigger').attr('style','display:none');
	            	 $('#tblAppendGrid_date_to_'+uq+'_tigger').attr('style','display:none');
	            	 $('#tblAppendGrid_date_from_'+uq+'_date').attr('readonly',true);
	            	 $('#tblAppendGrid_date_to_'+uq+'_date').attr('readonly',true);
	            	 $('#tblAppendGrid_date_from_'+uq+'_date').attr('readonly',true);
	            	 $('#tblAppendGrid_rate_'+uq).attr('readonly',true);
	            	 $('#tblAppendGrid_symbol_'+uq).attr('disabled',true);
	            	 var date_to=$('#tblAppendGrid_date_to_'+uq+'_date').val();
	            	 date_to = new Date(date_to.replace(pattern,'$3-$2-$1'));
	            	 date_to.setDate(date_to.getDate() + 1);
	            	 uq = $('#tblAppendGrid').appendGrid('getUniqueIndex', addedRowIndex);
	            	 $('#tblAppendGrid').appendGrid('setCtrlValue', 'date_from', addedRowIndex, formattedDate(date_to));
	            	 $('#tblAppendGrid_date_from_'+uq+'_tigger').attr('style','display:none');
	                 $('#tblAppendGrid_date_from_'+uq+'_date').attr('readonly',true);
	                
	            } else {
	            	alert('Wypełnij poprawnie wcześniejszy wpis!');
	            	$('#tblAppendGrid').appendGrid('removeRow', addedRowIndex);
	            }
            }
        },
        afterRowRemoved: function (caller, rowIndex) {
        	var rowOrder = $('#tblAppendGrid').appendGrid('getRowOrder');
        	uq = rowOrder[rowOrder.length - 1]
        	 $('#tblAppendGrid_date_to_'+uq+'_tigger').attr('style','display:inline');
        	 $('#tblAppendGrid_date_to_'+uq+'_date').attr('readonly',false);
        	 $('#tblAppendGrid_rate_'+uq).attr('readonly',false);
        	 $('#tblAppendGrid_symbol_'+uq).attr('disabled',false);
        },
        hideButtons: {
            
        	moveUp: true,
        	moveDown: true,
        	remove: true,
            insert: true,
         
        }
    });
    // wczytywanie danych do tabelki
    LoadDataFromInput();
    // hide css classes
    $('thead').removeClass('ui-widget-header');
    $('td').removeClass('ui-widget-header');
    $('tbody').removeClass('ui-widget-content');
    $('td').removeClass('ui-widget-content');
    $('tfoot').removeClass('ui-widget-header');
}

function formattedDate(date) {
    var d = new Date(date || Date.now()),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [day, month, year].join('.');
}

function LoadDataFromInput(){
    var pos = $.parseJSON($("input[name='positions']").val());
    $('#tblAppendGrid').appendGrid('load', pos);

    var count = $('#tblAppendGrid').appendGrid('getRowCount');

    for (var i = 0; i < count; i++) {

        var data2 = $('#tblAppendGrid').appendGrid('getRowValue', i);

        $('#tblAppendGrid').appendGrid('setCtrlValue', 'rate', i, FormatNumber(data2.rate));
        if(i<(count-1)){
	   	 var uq = $('#tblAppendGrid').appendGrid('getUniqueIndex', i);
		 $('#tblAppendGrid_date_from_'+uq+'_tigger').attr('style','display:none');
		 $('#tblAppendGrid_date_to_'+uq+'_tigger').attr('style','display:none');
		 $('#tblAppendGrid_date_from_'+uq+'_date').attr('readonly',true);
		 $('#tblAppendGrid_date_to_'+uq+'_date').attr('readonly',true);
		 $('#tblAppendGrid_rate_'+uq).attr('readonly',true);
		 $('#tblAppendGrid_symbol_'+uq).attr('disabled',true);
        } else {
       	 var uq = $('#tblAppendGrid').appendGrid('getUniqueIndex', i);
        	 $('#tblAppendGrid_date_from_'+uq+'_tigger').attr('style','display:none');
    		 
    		 $('#tblAppendGrid_date_from_'+uq+'_date').attr('readonly',true);
    		 
        }
    }
}