/**
 * Created by neosoft on 20/11/14.
 */
$(document).ready(function (){

    var base_url = window.location.origin;
    var previous_id = $("#previous_id").val();
    $("#add_promo").submit(function(e){
        var system_base_url = $("#system_base_url").val();
        var count = fnCheckIssueNumbers(system_base_url);
        var numberOfMagazine = $("#num_mag").val();
        if (numberOfMagazine == 0) {
            $("#promo_issue_block").html("Please select at least one magazine to proceed");
            count = 1;
        }

        if(count > 0) {
            e.preventDefault();
        }
    });

    $("#addCampaign_promo1").submit(function(e){
        var CurrentMagazineCount = parseInt($("label[for='totalnumbers']").text());
        var previous_id = $("#previous_id").val();
        var checkDuplicateYear = fnCheckDuplicateYear();
        if (checkDuplicateYear > 0) {
            return false;
        }

        var amount = $("#addCampaigncamp_amount").val();
        if (validateDecimal(amount) == false) {
            $("#promo_issue_error").html("Amount Should be an integer value");
            $("#addCampaigncamp_amount").css('border-color', 'red');
            return false;
        }

        /*if (! (amount % 1 === 0)) {
            $("#promo_issue_error").html("Amount Should be an integer value");
            $("#addCampaigncamp_amount").css('border-color', 'red');
            return false;
        }*/

        //var startIssue = parseInt($("#addCampaignissue1").val());
        var startIssue = $("#addCampaignissue1").val();
        /**if (! (startIssue % 1 === 0)) {
            $("#promo_issue_error").html("Start Issue value should be an integer");
            $("#addCampaignissue1").css('border-color', 'red');
            return false;
        }**/

        //var endIssue = parseInt($("#addCampaignissue2").val());
        var endIssue = $("#addCampaignissue2").val();
        /**if (! (endIssue % 1 === 0)) {
            $("#promo_issue_error").html("End Issue value should be an integer");
            $("#addCampaignissue2").css('border-color', 'red');
            return false;
        }**/

        var TotalIssue = parseInt($("#edit_no_issues").val());
        if (! (TotalIssue % 1 === 0)) {
            $("#promo_issue_error").html("Total Issue value should be an integer");
            $("#edit_no_issues").css('border-color', 'red');
            return false;
        }

        var endIssueValue = fnCheckEndIssue();
        if (endIssueValue > 0) {
            return false;
        }

        if(checkDuplicateYear > 0) {
            e.preventDefault();
        } else {
            var strMagazineId = $("#addCampaignmagazine").val();
            var strMagazineCode = $("#addCampaignmagazine option:selected").text();
            var startIssue = $("#addCampaignissue1").val();
            var endIssue = $("#addCampaignissue2").val();
            var TotalIssue = $("#edit_no_issues").val();
            var mag_amount = $("#addCampaigncamp_amount").val();
            var mag_start_date = $("#addCampaigndate1").val();
            var mag_end_date = $("#addCampaigndate2").val();
            var mag_no_year = $("#addCampaignnumber_of_year").val();
            var mag_no_copies = $("#addCampaignnumber_of_copies").val();
            var numYears = new Array();
            var strAction = "$(this).closest('tr').remove()";

            var purpose = $("#purpose").val();

            // This code block for Edit campaign Details Scenario.
            if (purpose == 'edit') {
                var intCampMagId = $('#used_camp_id').val();
                var intCampId = $('#used_code').val();
                var usedRowId = $("#used_row").val();
                var strNewAction = "return fnGetDetails("+intCampMagId+","+intCampId+","+usedRowId+")";
                var strNewHTMl = '<td class="text-center" ><input type="text" class="form-control" name="magezine_code[]" value="'+strMagazineId +'" readonly/></td>'+
                                '<td class="text-center"><input type="text" class="form-control validate[required,custom[integer],min[1]] text-input" name="camp_no_of_year[]" value="'+mag_no_year +'" readonly/></td> ' +
                                '<td class="text-center"><input type="text" class="form-control validate[required,custom[integer],min[1]] text-input" name="camp_no_of_copies[]" value="'+mag_no_copies +'" readonly/></td> ' +
                                '<td class="text-center"><input type="text" class="form-control" name="camp_amount[]" value="'+mag_amount +'" readonly/></td>' +
                                '<td class="text-center" ><input type="text" class="form-control validate[required] text-input" name="camp_start_date[]" value="'+mag_start_date +'" readonly/></td>' +
                                '<td class="text-center"><input type="text" class="form-control validate[required] text-input" name="camp_end_end[]" value="'+mag_end_date +'" readonly/></td> ' +
                                '<td class="text-center" ><input type="text" class="form-control" name="camp_start_issue[]" value="'+startIssue +'" readonly/></td>' +
                                '<td class="text-center"><input type="text" class="form-control" name="camp_end_issue[]" value="'+endIssue +'" readonly/></td> ' +
                                '<td class="text-center"><input type="text" class="form-control validate[required] text-input" name="camp_total_issue[]" value="'+TotalIssue +'" readonly/></td> ' +


                                "<td class='text-center'><input type='button' onClick="+ strAction +" value='Delete'></td>";
                strNewHTMl = strNewHTMl + '<td class="text-center"><a href="#update_camp_details" data-toggle="modal" onclick="'+strNewAction+'"><input type="button" value="Edit"></a></td>';

                var row = '#row'+usedRowId;
                $(row).html(strNewHTMl);
                $("#num_mag").val('1');
                $('#update_camp_details .close').trigger('click');
                return false;
            } // End Edit

            // This code block for Add campaign Details Scenario.
            else {
                var strNewHTMl = '<tr><td class="text-center" ><input type="text" class="form-control" name="magezine_code[]" value="'+strMagazineCode +'" readonly/></td>'+
                    '<td class="text-center"><input type="text" class="form-control validate[required,custom[integer],min[1]] text-input" name="camp_no_of_year[]" value="'+mag_no_year +'" readonly/></td> ' +
                    '<td class="text-center"><input type="text" class="form-control validate[required,custom[integer],min[1]] text-input" name="camp_no_of_copies[]" value="'+mag_no_copies +'" readonly/></td> ' +
                    '<td class="text-center"><input type="text" class="form-control" name="camp_amount[]" value="'+mag_amount +'" readonly/></td>' +
                    '<td class="text-center" ><input type="text" class="form-control validate[required] text-input" name="camp_start_date[]" value="'+mag_start_date +'" readonly/></td>' +
                    '<td class="text-center"><input type="text" class="form-control validate[required] text-input" name="camp_end_end[]" value="'+mag_end_date +'" readonly/></td> ' +
                    '<td class="text-center" ><input type="text" class="form-control" name="camp_start_issue[]" value="'+startIssue +'" readonly/></td>' +
                    '<td class="text-center"><input type="text" class="form-control" name="camp_end_issue[]" value="'+endIssue +'" readonly/></td> ' +
                    '<td class="text-center"><input type="text" class="form-control validate[required] text-input" name="camp_total_issue[]" value="'+TotalIssue +'" readonly/></td> ' +



                    "<td class='text-center'><input type='button' onClick="+ strAction +" value='Delete'></td></tr>";
                $("#list_new_magazines").append(strNewHTMl);
                $("label[for='totalnumbers']").text(CurrentMagazineCount + 1);
                $("#num_mag").val(1);
                $('#nnn .close').trigger('click');
                return false;
            }
        }

        return false;
    });


    $("#addCampaignnumber_of_year").change(function(){
        $("#camp_amount").val("");
        var intMagazineId = $("#addCampaignmagazine").val();
        var intNumberOfYear = $("#addCampaignnumber_of_year").val();
        var systemBaseUrl = $("#system_base_url").val();
        if (intMagazineId != "" && intNumberOfYear != "") {
            $.ajax({
                url:systemBaseUrl+"index.php/promotion/add_new_magazine",
                'data' : {
                    'prev_ids' :intMagazineId,
                    'no_of_years': intNumberOfYear
                },
                'type' : 'GET',
                success:function(result){
                    $("#addCampaigncamp_amount").val(result);
                    $('#addCampaigncamp_amountFirstTime').val(result);
                    calculateNoOfCopiesAmount();
                }
            });
        }
    });


    $(document).on('change', '#addCampaignnumber_of_copies', function () {
        calculateNoOfCopiesAmount();
    });

    

});

function calculateNoOfCopiesAmount() {
    var addCampaigncamp_amountFirstTime = $('#addCampaigncamp_amountFirstTime').val();
    var addCampaignnumber_of_copies = $('#addCampaignnumber_of_copies').val();
    if(addCampaignnumber_of_copies != '' && addCampaigncamp_amountFirstTime != '') {
        var totalCopiesAmount = addCampaignnumber_of_copies * addCampaigncamp_amountFirstTime;
        $('#addCampaigncamp_amount').val(totalCopiesAmount);    
    }
}

function validateDecimal(value)    {
    var RE = new RegExp(/^\d+(?:\.\d{1,2})?$/);
    if(RE.test(value)){
       //return true;
    }else{
       return false;
    }
}
function fnCheckIssueNumbers(system_base_url)
{
    var system_base_url = $("#system_base_url").val();
    var previous_id = $("#previous_id").val();
    var promoCode = $("#campaign_code").val();
    var numberOfMagazine = $("#num_mag").val();
    var count = 0;
    if (promoCode != previous_id) {
        $.ajax({
            url:system_base_url+"index.php/promotion/fnCheckPromotionCode",
            'type' : 'GET',
            async:false,
            'data' : {
                'promotion_id' :promoCode
            },
            success:function(result){
                if (result > 0) {
                    $("#promo_code_block").html("Campaign Code already in use");
                    $("#campaign_code").css('border-color', 'red');
                    count = 1;
                }
            }
        });
    }

    return count;
}

function fnCheckEndIssue(intFlag)
{
    var valueOFStart = parseInt($("#addCampaignissue1").val());
    var valueOFEnd = parseInt($("#addCampaignissue2").val());
    var count = 0;
    if (valueOFEnd < valueOFStart) {
        count = 1;
        $("#promo_issue_error").html("End Issue number must be greater than start issue number");
        $("#addCampaignissue2").css('border-color', 'red');
    }
    return count;
}

function fnCheckDuplicateYear()
{
    var numyrs = new Array();
    var intErrorCount = 0;
    $("select[name^='magezine_sub_no_years[]']").each(function(index, element){
        numyrs.push($(element).val());
    });

    var recipientsArray = numyrs.sort();

    var reportRecipientsDuplicate = [];
    for (var i = 0; i < recipientsArray.length - 1; i++) {
        if (recipientsArray[i + 1] == recipientsArray[i]) {
            reportRecipientsDuplicate.push(recipientsArray[i]);
        }
    }

    if (reportRecipientsDuplicate.length > 0)
    {
        var html = "<h5>Please select unique number of year for each subscription package</h5>";
        $("#year_error").html($(html));
        intErrorCount = 1;
    }

    return intErrorCount;
}
