$(document).ready(function(){
    // This function used to validate the subscriber type and its associate information.
	$('#subscriber_type').change(function() {

        var school_name = "";
        var company_name = "";
        var guardian_name = "";
        var guardian2_name = "";
        var other_details = "";
        var teacher_name = "";

        // Get the company name
        if ($('#comp_name').val() != null) {
            company_name = $('#comp_name').val();
        }
        // Get the guard name
		if ($('#guard_name').val() != null) {
            guardian_name = $('#guard_name').val();
        }

        // Get the guard2 name
		if ($('#guard2_name').val() != null) {
            guardian2_name = $('#guard2_name').val();
        }

        // Get the school name
        if ($('#school_name').val() != null) {
            school_name = $('#school_name').val();
        }

        // Get the other details
        if ($('#other_details').val() != null) {
            other_details = $('#other_details').val();
        }

        $('#sub_details').text('');
        $('#sub_school_details').text('');
        $('#sub_other_details').text('');
        $('#sub_teacher_details').text('');
        if ($('#subscriber_type').val() == '2') {
			var html = '<label  class="col-sm-3 control-label text-left">School Library Name: </label>' + '<div class="col-sm-8"><input type="text" class="form-control validate[required] text-input" value="'+ company_name +'" name= "cname"/></div>';
			$('#sub_details').html($(html));
        } else if($('#subscriber_type').val() == '3') {
			var html = '<label  class="col-sm-3 control-label text-left">Guardian Name: </label>' + '<div class="col-sm-9"><input type="text" class="form-control " value="'+ guardian_name +'" name= "gname"/></div>' + '<br><label  class="col-sm-3 control-label text-left">Guardian(2) Name: </label>' + '<br><div class="col-sm-9"><input type="text" class="form-control validate[required] text-input" value="'+ guardian2_name +'" name= "gname2"/></div>';
            var school = '<label  class="col-sm-3 control-label text-left">School Name: </label>' + '<div class="col-sm-9"><input type="text" class="form-control " value="'+ school_name +'" name= "sname"/></div>';
            var teacher = '<label  class="col-sm-3 control-label text-left">Teacher Name: </label>'+ '<div class="col-sm-9"><input type="text" class="form-control" value="'+ teacher_name +'" name= "tname"/></div>';
            $('#sub_details').html($(html));
            $('#sub_school_details').html($(school));
            $('#sub_teacher_details').html($(teacher));
		} else if($('#subscriber_type').val() == '4') {
            var html = '<label  class="col-sm-3 control-label text-left">Details: </label>' + '<div class="col-sm-8"><input type="text" class="form-control validate[required] text-input" value="'+ other_details +'" name= "other_details"/></div>';
            $('#sub_other_details').html($(html));
        }
		
	});

    // This function used to validate the subscriber information.
    $("#submit_sub").click(function(){
        $("#give_msgs").html();
        $("#all_msgs").html();
        var system_base_url = $("#system_base_url").val();
        var sub_image = $("#sub_image").val();
        var sub_nric = $("#sub_nric").val();
        var sub_email = $("#sub_email").val();
        var first_name = $("#sub_first_name").val();
        var last_name = $("#sub_last_name").val();
        var dob = $("#sub_dob").val();

        var bool_result = 0;
        var msg = "";
        //Check file type
        var image_result = fnCheckFileType();
        if (image_result > 0){
            msg = msg + "<p style='color:red'>Invalid File Type</p>";
            bool_result = 1;
        }

        //Check whether the email exist
        /**if (sub_email != "") {
            var email_exist = fnCheckEmailWithAjax(system_base_url);
            if (email_exist > 0){
                msg = msg + "<p style='color:red'>Given email address is already exist</p>"
                $("#sub_email").css('border-color', 'red');
                bool_result = 1;
            }
        }**/

        //Check for the unique NRIC
        if (sub_nric != "") {
            var nric_exist = fnCheckNricWithAjax(system_base_url);
            if (nric_exist > 0){
                msg = msg + "<p style='color:red'>Given NRIC is already exist</p>"
                $("#sub_nric").css('border-color', 'red');
                bool_result = 1;
            }
        }

        // Now check whether the combinition of "First Name", "Last Name", "Date of Birth" will be repeated or not.

        if (first_name != "" && last_name != "" && dob != "") {
            var nric_exist = fnCheckCombinitionWithAjax(system_base_url, first_name, last_name, dob);
            if (nric_exist > 0){
                msg = msg + "<p style='color:red'>Combination of first name, last name and birth date is already exist</p>"
                bool_result = 1;
            }
        }

        if (bool_result > 0) {
            $("#give_msgs").html(msg);
            return false;
        }

        /**var return_message = fnValidateFormData();
        if (return_message != "") {
            var tableValue = "<button id='cross_error' class='close' aria-hidden='true' type='button'>×</button><table class='table table-white table-vertical-center margin-none table-striped footable' style='color: red;text-align: left'>";
            tableValue = tableValue + return_message;
            tableValue = tableValue + "</table>";
            $("#all_msgs").html(tableValue);
            return false;
        }**/
    });

    $("#cross_error").click(function() {
        $("#all_msgs").hide();
    });

    $("#magezine_id").focus(function(){
        $("#sub_email").css('border-color', 'white');
        $("#give_msgs").html("");
    });


    // This function used to get the details of requested magazine.
    $("#sub_magazine_id").change(function(){
        $("#sub_single_magazine").html();
        var strMagazineId = $("#sub_magazine_id").val();
        var system_base_url = $("#system_base_url").val();
        if (strMagazineId != "") {
            $.ajax({
                url:system_base_url+"index.php/subscriber/fnGetMagazineDetails",
                'type' : 'GET',
                async:false,
                'data' : {
                    'strMagazineId' :strMagazineId
                },
                success:function(result){
                    $("#ajax_content").html(result);
                    $('#ajax_content .date').datepicker();
                }
            });
        }
    });

    // This function used to get the associated magazines.
    $("#promo_id").change(function() {
        $('#ajax_content').html("");
        $('#append_magazine').html("");
        $('#table_body_camp').html("");
        var strCampId = $("#promo_id").val();
        var strSubId = $("#subscriber_id").val();
        var system_base_url = $("#system_base_url").val();
        if (strCampId != "") {
            $.ajax({
                url:system_base_url+"index.php/subscriber/fnGetAssociateMagazines",
                'type' : 'GET',
                async:false,
                'data' : {
                    'intCampaignId' :strCampId,
                    'sub_id' :strSubId
                },
                success:function(result){
                    $("#append_magazine").html("");
                    $("#append_magazine").append(result);
                    //result
                }
            });
        }
    });

    // This function used to add multiple magazines to the selected campaign while creating the campaign.
    $("#camp_number_years").change(function(){
        // Refresh the fields value.
        $("#issue1").val("");
        $("#issue2").val("");
        $("#camp_start_date").val("");
        $("#camp_end_date").val("");
        $("#amount").val("");
        $("#no_issues").val("");
        //$("#camp_number_years").val("");
        //End

        var strMagazineId = $("#sub_magazine_camp").val();
        var strCampId = $("#promo_id").val();
        var intNumberOfYear = $("#camp_number_years").val();
        var add_magazine_campaign = $("#add_magazine_campaign").val();
        var system_base_url = $("#system_base_url").val();

        if (strMagazineId != "") {
            $.ajax({
                url:system_base_url+"index.php/subscriber/fnGetRelatedMagazineDetails",
                'type' : 'GET',
                async:false,
                'data' : {
                    'strMagazineId' :strMagazineId,
                    'strCampaignId' : strCampId,
                    'numberOfYears': intNumberOfYear,
                    'add_magazine_campaign' : add_magazine_campaign
                },
                success:function(result){
                    var arrResultSet = jQuery.parseJSON(result);
                    $("#issue1").val(arrResultSet.start_issue);
                    $("#issue2").val(arrResultSet.end_issue);
                    $("#camp_start_date").val(arrResultSet.start_date);
                    $("#camp_end_date").val(arrResultSet.end_date);
                    $("#amount").val(arrResultSet.amount);
                    //$("#camp_number_years").val(arrResultSet.no_of_year);
                    $("#no_issues").val(arrResultSet.no_of_issue);
                    //console.log(arrResultSet);
                }
            });
        }
        //return intCount;
    });

    /**
     * // This function used to add multiple magazines to the selected campaign while creating the campaign.
     $("#sub_magazine_camp").change(function(){
        // Refresh the fields value.
        $("#issue1").val("");
        $("#issue2").val("");
        $("#camp_start_date").val("");
        $("#camp_end_date").val("");
        $("#amount").val("");
        $("#camp_number_years").val("");
        //End

        var strMagazineId = $("#sub_magazine_camp option:selected").val();
        var strCampId = $("#promo_id").val();
        var intNumberOfYear = $("#sub_options").val();
        var add_magazine_campaign = $("#add_magazine_campaign").val();
        var system_base_url = $("#system_base_url").val();

         if (strMagazineId != "") {
            $.ajax({
                url:system_base_url+"index.php/subscriber/fnGetMagazinesDetails",
                'type' : 'GET',
                async:false,
                'data' : {
                    'strMagazineId' :strMagazineId,
                    'strCampaignId' : strCampId,
                    'intNumYear': intNumberOfYear,
                    'add_magazine_campaign' : add_magazine_campaign
                },
                success:function(result){
                    var arrResultSet = jQuery.parseJSON(result);
                    $("#issue1").val(arrResultSet.start_issue);
                    $("#issue2").val(arrResultSet.end_issue);
                    $("#camp_start_date").val(arrResultSet.start_date);
                    $("#camp_end_date").val(arrResultSet.end_date);
                    $("#amount").val(arrResultSet.amount);
                    $("#camp_number_years").val(arrResultSet.no_of_year);
                    $("#no_issues").val(arrResultSet.no_of_issue);
                    //console.log(arrResultSet);
                }
            });
        }
        //return intCount;
    });
     */

    // This function used to add multiple magazines to the selected campaign while subscribing the campaign.
    $("#btn_submit_campaing").click(function(e){
        var valueOFStart = "";
        var valueOFEnd = "";
        var CheckErrors = 0;
        valueOFStart = $("#issue1").val();
        valueOFEnd = $("#issue2").val();
        /*var CheckErrors = fnCheckEndIssue(valueOFStart, valueOFEnd);
        if (CheckErrors > 0) {
            return false;
        }*/
        /**if (valueOFEnd <=  valueOFStart)
        {
            $("#promo_issue_error").html("End Issue number must be greater than start issue number");
            $("#issue2").css('border-color', 'red');
            return false;
        }*/
        if (CheckErrors == 0) {
            var strMagazineId = $("#sub_magazine_camp option:selected").text();
            var strHidenMagazineId = $("#sub_magazine_camp").val();
            var mag_amount = $("#amount").val();
            var startIssue = $("#issue1").val();
            var endIssue = $("#issue2").val();
            var start_date = $("#camp_start_date").val();
            var TotalIssue = $("#no_issues").val();
            var end_date = $("#camp_end_date").val();
            var numberOfYears = $("#camp_number_years").val();
            var strAction = "$(this).closest('tr').remove()";
            var intRowId = 'row'+Math.floor((Math.random() * 100) + 1);
            var editAction = "fnEditCampaignDetails('"+intRowId+"')";
            var strNewHTMl = '<tr id="'+intRowId+'"><td class="text-center"><input type="hidden" class="form-control" name="magezine_ids[]" value="'+strHidenMagazineId +'" /></td>'+
                '<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" name="numberOfYear[]" value="'+numberOfYears +'" readonly/></a></td>'+
                '<td class="text-center"><input type="text" class="form-control" name="amount[]" value="'+mag_amount +'" readonly/></td>' +
                '<td class="text-center"><input type="text" class="form-control" name="camp_start_date[]" value="'+start_date +'" readonly/></td> ' +
                '<td class="text-center"><input type="text" class="form-control" name="camp_end_date[]" value="'+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" name="camp_total_issue[]" value="'+TotalIssue +'" readonly/></td> ' +
                "<td class='text-center'><a href='#edit_campaign_details' id='add_new_Magazine' data-toggle='modal' onclick=" + editAction +"><input type='button' value='edit'></td>" +
                "<td class='text-center'><input type='button' onClick="+ strAction +" value='Delete'></td></tr>";
           $("#list_new_magazines").append(strNewHTMl);
                $('#nnn .close').trigger('click');
            return false;
        } else {
            return false;
        }


        return false;
    });
    $("#btn_edit_campaing").click(function(e){
        var valueOFStart = "";
        var valueOFEnd = "";
        var CheckErrors = 0;
        valueOFStart = $("#issue1s").val();
        valueOFEnd = $("#issue2s").val();
        /*var CheckErrors = fnCheckEndIssue(valueOFStart, valueOFEnd);
        if (CheckErrors > 0) {
            return false;
        }*/
        /*if (valueOFEnd <=  valueOFStart)
        {
            $("#edit_promo_issue_error").html("End Issue number must be greater than start issue number");
            $("#issue2s").css('border-color', 'red');
            return false;
        }*/
        if (CheckErrors == 0) {
            var strMagazineId = $("#sub_magazine_camps").val();
            var strUsedMagazineId = $("#UsedMagazineCodes").val();
            var mag_amount = $("#amounts").val();
            var startIssue = $("#issue1s").val();
            var endIssue = $("#issue2s").val();
            var TotalIssue = $("#edit_no_issues").val();
            var start_date = $("#camp_start_dates").val();
            var end_date = $("#camp_end_dates").val();
            var row_id_edit = $("#row_id_edits").val();
            var numberOfYears = $("#camp_number_yearss").val();
            var strAction = "$(this).closest('tr').remove()";
            var editAction = "fnEditCampaignDetails('"+row_id_edit+"')";
            var strNewHTMl = '<td class="text-center"><input type="hidden" class="form-control" name="magezine_ids[]" value="'+strUsedMagazineId +'" /></td>'+
                '<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" name="numberOfYear[]" value="'+numberOfYears +'" readonly/></a></td>'+
                '<td class="text-center"><input type="text" class="form-control" name="amount[]" value="'+mag_amount +'" readonly/></td>' +
                '<td class="text-center"><input type="text" class="form-control" name="camp_start_date[]" value="'+start_date +'" readonly/></td> ' +
                '<td class="text-center"><input type="text" class="form-control" name="camp_end_date[]" value="'+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" name="camp_total_issue[]" value="'+TotalIssue +'" readonly/></td> ' +
                "<td class='text-center'><a href='#edit_campaign_details' id='add_new_Magazine' data-toggle='modal' onclick=" + editAction +"><input type='button' value='edit'></td>" +
                "<td class='text-center'><input type='button' onClick="+ strAction +" value='Delete'></td>";
            var row = '#'+row_id_edit;
            $(row).html(strNewHTMl);
            $('#edit_campaign_details .close').trigger('click');
            $("#num_mag").val('1');

            return false;
        } else {
            return false;
        }


        return false;

    });


    //Code block to validate information while updating subscribed Magazine Information.
    $("#edit_subscribed_magezine").submit(function(){
        var intStartIssue = parseInt($("#issue1s").val());
        var intEndIssue = parseInt($("#issue2s").val());
        var intAmount = parseInt($("#amounts").val());

        //validate start Issue number
        if (intStartIssue == 0) {
            $("#promo_issue_error").html("Start Issue number is not a valid value");
            $("#issue1s").css('border-color', 'red');
            return false;
        }

        //validate End Issue number
        if (intEndIssue == 0) {
            $("#promo_issue_error").html("End Issue number is not a valid value");
            $("#issue2s").css('border-color', 'red');
            return false;
        }

        //validate Amount
        if (intAmount == 0) {
            $("#promo_issue_error").html("Amount is not a valid value");
            $("#issue1s").css('border-color', 'red');
            return false;
        }

        // Now check whether the start issue is greater than the end issue;
        if (intStartIssue >= intEndIssue) {
            $("#promo_issue_error").html("Start Issue number can not be greater than End Issue");
            $("#issue2s").css('border-color', 'red');
            return false;
        }

        return true;
    });


    $("#country_code").change(function(){
        var intCountryCode = $("#country_code").val();
        if (intCountryCode > 0) {
            $("#phone_no").html("+"+intCountryCode);
        }
    });

    $("#country_code_mobile").change(function(){
        var intCountryCode = $("#country_code_mobile").val();
        if (intCountryCode > 0) {
            $("#mobile_no").html("+"+intCountryCode);
        }
    });

$(document).on('change','#selStatus',function(){
        var status = $('#selStatus').val();
        if(status == ''){
            $('#txtComment,.lblComments').hide();
            $('#btnSend').hide();
        }else if(status == '2'){
            $('#txtComment,.lblComments').show();
            $('#btnSend').show();
        }else if(status == '0'){
            $('#txtComment,.lblComments').hide();
            $('#btnSend').show();
        }else if(status == '1'){
            $('#txtComment,.lblComments').hide();
            $('#btnSend').show();
        }
    });

    $(document).on('click','#btnSend',function(){
        var lang = $(this).attr('lang');
        var status = $('#selStatus').val();
        $('#txtComment').css('border','1px solid #cccccc');
        if(status == '2'){
            var txtComment = $('#txtComment').val();
            if(txtComment == '' || txtComment == null){
                $('#txtComment').css('border','1px solid red');
                return false;
            }

            fnSendTrpInfo(lang,status,txtComment);
        }else if(status == '0'){
            fnSendTrpInfo(lang,status,'');
        }else if(status == '1'){
            fnSendRnewPopup(lang);
        }

    });


    $(document).on('change', '#camp_number_copiesss', function () {
        calculateNoOfCopiesAmountEdit();
    });

    $("#camp_number_yearss").change(function(){
        alert(1);
        $("#omamount").val("");
        var intMagazineId = $("#sub_magazine_camps_id").val();
        var intNumberOfYear = $("#camp_number_yearss").val();
        var systemBaseUrl = $("#system_base_url").val();
        if (intMagazineId != "" && intNumberOfYear != "") {
            $.ajax({
                url:"http://nurturecraftmagazines.com/magazine/index.php/promotion/add_new_magazine",
                'data' : {
                    'prev_ids' :intMagazineId,
                    'no_of_years': intNumberOfYear
                },
                'type' : 'GET',
                success:function(result){
                    $('#omamount').val(result);
                    calculateNoOfCopiesAmountEdit();
                }
            });
        }
    });


});

function calculateNoOfCopiesAmountEdit() {
    var omamount = $('#omamount').val();
    var camp_number_copiesss = $('#camp_number_copiesss').val();
    if(camp_number_copiesss != '' && omamount != '') {
        var totalCopiesAmount = camp_number_copiesss * omamount;
        $('#amounts').val(totalCopiesAmount);    
    }
}

function fnSendRnewPopup(trp_data){
    var trp_data_ = trp_data.split('---');
    var system_base_url = $("#system_base_url").val();
window.location.href = system_base_url+'index.php/subscriber/subscribe_product?user_id='+trp_data_[1]+'&tr_id='+trp_data_[0];

 

}

function fnSendTrpInfo(trp_data,status,comment){
    var system_base_url = $("#system_base_url").val();
    $.ajax({
        url:system_base_url+"index.php/subscriber/fnUpdateTransaction",
        'type' : 'POST',
        async:false,
        'data' : {
            'trp_data' :trp_data,
            'status'   :status,
            'comment'  :comment
        },
        success:function(result){
            if (result == 0) {
                $('span.error_msg_for_trp').html('<b style="color:red;">Please provide valid transaction information</b>');
            }else if(result == 1) {
                $('#renew_mag').html('<b style="color:green;padding: 10px;display: inline-block;text-align: center;width: 100%;">Information Successfully Sent..!!</b>');
                setTimeout(function(){
                    location.reload();
                }, 1500);
            }
        }
    });
}

function fnCheckFileType()
{
    var intCount = 0;
    var ext = $('#sub_image').val().split('.').pop().toLowerCase();
    if (ext != "") {
        if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
            intCount = 1;
        }
    }

    return intCount;
}

function fnCheckEmailWithAjax (system_base_url)
{
    var email = $("#sub_email").val();
    var prevEmail = $("#prevEmail").val();

    var base_url = window.location.origin;
    var intCount = 0;
    if (prevEmail != email) {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnCheckEmailExist",
            'type' : 'GET',
            async:false,
            'data' : {
                'email' :email
            },
            success:function(result){
                if (result > 0) {
                    intCount = result;
                }
            }
        });
    }
    return intCount;
}

function fnCheckNricWithAjax (system_base_url)
{
    var nric = $("#sub_nric").val();
    var prevNRIC = $("#prevNric").val();
    var base_url = window.location.origin;
    var intCount = 0;
    if (prevNRIC != nric) {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnCheckEmailExist",
            'type' : 'GET',
            async:false,
            'data' : {
                'email' :nric,
                'field':'nric'
            },
            success:function(result){
                if (result > 0) {
                    intCount = result;
                }
            }
        });
    }
    return intCount;
}

function fnCheckCombinitionWithAjax(system_base_url, first_name, last_name, dob)
{
    var prevFirstName = $("#prevFirstName").val();
    var prevLastName = $("#prevLastName").val();
    var prevDob = $("#prevDob").val();

    var Datevalue = 1;
    if (prevDob != ""){
        var arrStartDate = prevDob.split("-");
        var date1 = arrStartDate[0] + arrStartDate[1]+ arrStartDate[2];
        var arrEndDate = dob.split("-");
        var date2 = arrEndDate[0] + arrEndDate[1]+ arrEndDate[2];

        if (date1 == date2) {
            Datevalue = 0;
        }
    }


    var intCount = 0;
    if ((first_name != prevFirstName) || (prevLastName != last_name)) {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnCheckEmailExist",
            'type' : 'GET',
            async:false,
            'data' : {
                'first_name' :first_name,
                'last_name' :last_name,
                'dob' :dob,
                'field':'combinition'
            },
            success:function(result){
                if (result > 0) {
                    intCount = result;
                }
            }
        });
    }
    return intCount;
}

function fnValidateFormData()
{
    var sub_first_name = $("#sub_first_name").val();
    var sub_last_name =  $("#sub_last_name").val();
    var sub_dob = $("#sub_dob").val();
    var sub_nric = $("#sub_nric").val();
    var sub_email = $("#sub_email").val();
    var gender = $("#gender").val();
    var sub_phonno = $("#sub_phonno").val();
    var mobile_number = $("#mobile_number").val();
    var campaign = $("#campaign").val();
    var sub_home_block = $("#sub_home_block").val();
    var sub_home_unit_no = $("#sub_home_unit_no").val();
    var sub_home_street = $("#sub_home_street").val();
    var sub_home_country = $("#sub_home_country").val();
    var sub_home_city = $("#sub_home_city").val();
    var sub_home_code = $("#sub_home_code").val();
    var sub_block = $("#sub_block").val();
    var sub_unit_no = $("#sub_unit_no").val();
    var sub_street = $("#sub_street").val();
    var sub_code = $("#sub_code").val();

    var return_message = "";
    var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
    // check whether the first name contains any special characters.
    if (sub_first_name != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_first_name) == false) {
            return_message=  return_message + "<tr><td>First Name value contains special character</td></tr>";
        }
    }

    // check whether the first name contains any special characters.
    if (sub_last_name != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_last_name) == false) {
            return_message=  return_message + "<tr><td>Last Name value contains special character</td></tr>";
        }
    }

    // check whether the NRIC contains any special characters.
    if (sub_nric != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_nric) == false) {
            return_message=  return_message + "<tr><td>NRIC value contains special character</td></tr>";
        }
    }

    // check whether the Email contains any special characters.
    if (sub_email != "") {
        var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
        if(!pattern.test(sub_email)) {
            return_message=  return_message + "<tr><td>Please enter valid email address</td></tr>";
        }
    }

    // check whether the Phone number contains any special characters.
    if (sub_phonno != "") {
        if(!numericReg.test(sub_phonno)) {
            return_message=  return_message + "<tr><td>Phone number value contains special character</td></tr>";
        }
    }

    // check whether the Mobile number contains any special characters.
    if (mobile_number != "") {
        if(!numericReg.test(mobile_number)) {
            return_message=  return_message + "<tr><td>Mobile number value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_home_block != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_home_block) == false) {
            return_message=  return_message + "<tr><td>Home Address block value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_home_unit_no != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_home_unit_no) == false) {
            return_message=  return_message + "<tr><td>Home Address Unit number value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_home_code != "") {
        if(!numericReg.test(sub_home_code)) {
            return_message=  return_message + "<tr><td>Home Address code number value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_block != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_block) == false) {
            return_message=  return_message + "<tr><td>Mailing Address block value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_street != "") {
        if(/^[a-zA-Z0-9- ]*$/.test(sub_street) == false) {
            return_message=  return_message + "<tr><td>Mailing Address street value contains special character</td></tr>";
        }
    }

    // check whether the  contains any special characters.
    if (sub_code != "") {
        if(!numericReg.test(sub_code)) {
            return_message=  return_message + "<tr><td>Home Address code number value contains special character</td></tr>";
        }
    }

    return return_message;
}



function add_subscriber()
{
    var base_url = $("#system_base_url").val();
    var html = "<div align='center'><img src='"+base_url+"assets/images/loader.gif'/></div>";
    $("#tran_preview").html(html);
    $.ajax({
        url: base_url+"index.php/subscriber/add_subscriber",
        'type' : 'GET',
        success:function(result){
            $("#tran_preview").html(result);
            //alert(result);
        }
    });
}

function edit_subscriber(intUserId)
{
    var base_url = $("#system_base_url").val();
    var html = "<div align='center'><img src='"+base_url+"assets/images/loader.gif'/></div>";
    $("#edit_promo").html(html);
    $.ajax({
        url:  base_url+"index.php/subscriber/edit_subscriber",
        'data' : {
            'user_id' :intUserId
        },
        'type' : 'GET',
        success:function(result){
            $("#edit_promo").html(result);
        }
    });
}


function subscribe_magazine_wise(intUserId)
{
    var base_url = $("#system_base_url").val();
    var html = "<div align='center'><img src='"+base_url+"assets/images/loader.gifassets/images/loader.gif'/></div>";
    $("#sub_magazine").html(html);
    $.ajax({
        url:  base_url+"index.php/subscriber/subscribe_product",
        'data' : {
            'user_id' :intUserId,
            'type': 'magazine'
        },
        'type' : 'GET',
        success:function(result){
            $("#sub_magazine").html(result);
        }
    });
}



function subscribe_campaign_wise(intUserId)
{
    var base_url = $("#system_base_url").val();
    var html = "<div align='center'><img src='"+base_url+"assets/images/loader.gif'/></div>";
    $("#sub_campaign").html(html);
    $.ajax({
        url:  base_url+"index.php/subscriber/subscribe_product",
        'data' : {
            'user_id' :intUserId,
            'type': 'campaign'
        },
        'type' : 'GET',
        success:function(result){
            $("#sub_campaign").html(result);
        }
    });
}


function fnGetCampaignsMagazine()
{
    var strMagazineId = $("#camp_magazine_id").val();
    var strCampId = $("#promo_id").val();
    var system_base_url = $("#system_base_url").val();
    if (strMagazineId != "") {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnGetMagazineDetails",
            'type' : 'GET',
            async:false,
            'data' : {
                'strMagazineId' :strMagazineId,
                'intCampId':strCampId
            },
            success:function(result){
                $("#ajax_content").html(result);
            }
        });
    }
}

function renew_magazine(transaction_id, subscriber_id, magazine_code){
    $("#renew_mag").html('<div class="modal-dialog"><div class="modal-content"><div class="modal-header" align="left"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3 class="modal-title">Renew Details</h3></div><div class="modal-body"><div class="innerAll"><div class="innerLR"><label style="padding:0px 47px 0px 0px;">Status: </label><select id="selStatus" style="width: 50%;padding: 5px;border-color: #d4d4d4;"><option value="">Select</option><option value="2">Terminate</option><option value="0">Expire</option><option value="1">Renew</option></select><div></div><label style="padding:0px 20px 0px 0px;position: relative;top: -92px;display:none;" class="lblComments">Comments: </label><textarea id="txtComment" placeholder="Enter Comment.." cols="50" rows="5" style="display:none;padding: 5px;margin-top: 10px;border-color: #dedede;margin-left: 0em;"></textarea><div></div><button style="display:none;margin-left: 6.5em;margin-top: 10px;padding: 5px 15px 5px 15px;" class="btn btn-success" id="btnSend" lang="'+transaction_id+'---'+subscriber_id+'---'+magazine_code+'">Submit</button><span class="error_msg_for_trp"></span></div></div></div></div></div>');
}

function add_magazine_list()
{
    var strMagazineId = $("#camp_magazine_id").val();
    var strCampId = $("#promo_id").val();
    var intNumberOfYear = $("#sub_option").val();
    if (strCampId == "") {
        alert("Please select Campaign to proceed");
        location.reload();
    }
    var system_base_url = $("#system_base_url").val();
    var arrMagazines = new Array();
    $("input[name^='magezine_ids[]']").each(function(index, element){
        arrMagazines.push($(element).val());
    });
    if (strMagazineId != "") {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnGetAssociateMagazines",
            'type' : 'GET',
            async:false,
            'data' : {
                'intCampaignId' :strCampId,
                'flag':'magazine_dropdown',
                'intNumberOfYear' : intNumberOfYear,
                'arrUsedMagazines' : arrMagazines
            },
            success:function(result){
                $("#tran_preview2").html(result);
            }
        });
    }
}

function add_magazine_to_campaign()
{
    var strMagazineId = $("#camp_magazine_id").val();
    var strCampId = $("#promo_id").val();
    var intNumberOfYear = $("#sub_option").val();
    if (strCampId == "") {
        alert("Please select Campaign to proceed");
        location.reload();
    }
    var system_base_url = $("#system_base_url").val();
    if (strMagazineId != "") {
        $.ajax({
            url:system_base_url+"index.php/subscriber/fnAddCampaignMagazineSubscription",
            'type' : 'GET',
            async:false,
            'data' : {
                'intCampaignId' :strCampId,
                'intNumberOfYear' : intNumberOfYear
            },
            success:function(result){
                $("#tran_preview2").html(result);
            }
        });
    }
}


function fnCheckEndIssue(valueOFStart, valueOFEnd)
{
    var count = 0;


    if(!$.isNumeric(valueOFStart)) {
        count = 1;
        $("#promo_issue_error").html("Start Issue number is not a numeric value");
        $("#issue1").css('border-color', 'red');
        return count;
    }

    if(!$.isNumeric(valueOFEnd)) {
        count = 1;
        $("#promo_issue_error").html("End Issue number is not a numeric value");
        $("#issue2").css('border-color', 'red');
        return count;
    }
    return count;
}

function fnEditCampaignDetails(strRowId)
{
    var system_base_url = $("#system_base_url").val();
    var editMagazineId = $('#'+strRowId).children('td').eq(0).children().val();
    var editMagazineCode = $('#'+strRowId).children('td').eq(1).children().val();
    var editYears = $('#'+strRowId).children('td').eq(2).children().val();
    var editAmount = $('#'+strRowId).children('td').eq(3).children().val();
    var editStartDate = $('#'+strRowId).children('td').eq(4).children().val();
    var editEndDate = $('#'+strRowId).children('td').eq(5).children().val();
    var editStartIssue = $('#'+strRowId).children('td').eq(6).children().val();
    var editEndIssue = $('#'+strRowId).children('td').eq(7).children().val();
    var editTotalIssue = $('#'+strRowId).children('td').eq(8).children().val();



    $.ajax({
        url:system_base_url+"index.php/subscriber/fnUpdateCampaignMagazineInfo",
        'type' : 'GET',
        async:false,
        'data' : {
            'magazine_Id' :editMagazineId,
            'magazine_code' :editMagazineCode,
            'start_issue' :editStartIssue,
            'end_issue' :editEndIssue,
            'start_date' :editStartDate,
            'end_date' :editEndDate,
            'amount' :editAmount,
            'years' :editYears,
            'total_issue' :editTotalIssue,
            'row_id':strRowId
        },
        success:function(result){
            $("#tran_preview3").html(result);
        }
    });
}

function fnSendIndividualMails(mail_id)
{
    $("#recipient").val(mail_id);
    $("#message_desc").val("");
    $("#mail_subject").val("");
}

function send_ind_mail()
{
    var recipient = $("#recipient").val();
    var message = $("#message_desc").val();
    var mail_subject = $("#mail_subject").val();
    var system_base_url = $("#system_base_url").val();
    if (recipient == "") {
        alert("Please provide valid email address");
        return false;
    }
    if (message == "") {
        alert("Please provide Message");
        return false;
    }
    if (mail_subject == "") {
        alert("Please provide valid email subject");
        return false;
    }
    $.ajax({
        url:system_base_url+"index.php/subscriber/fnSendIndividualMail",
        'type' : 'GET',
        async:false,
        'data' : {
            'recipient' :recipient,
            'message' :message,
            'mail_subject' :mail_subject
        },
        success:function(result){
            alert("Mail send successfully");
            $('#send_individual_mail .close').trigger('click');
        }
    });
}

function fnManageText()
{
    var showChar = 500; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";


    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);

            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });


}

function fnSetSubscriberId(strSubscriberId)
{
    $("#subscriber_id_process").val(    );
    $("#subscriber_id_process").val(strSubscriberId);
    return true;
}