/**
 * Created by neosoft on 20/11/14.
 */
$('#btnSubmit').click(function(){
    var numyrs = new Array();
    var system_base_url = $("#system_base_url").val();
    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;
    }

    var magazineCode = $("#magezine_id").val();
    var prevMagazineId = $("#preMagId").val();
    if (prevMagazineId != magazineCode){
        var magazineId = fnGetDataFromAjax(magazineCode, system_base_url);
        if (magazineId > 0) {
            $("#promo_code_block").html("<span style='color:red'>Magazine Code already in use</span>");
            $("#magezine_id").css('border-color', 'red');
            intErrorCount = 1;
        }
    }


    if ($('#magezine_image').length > 0) {
        var fnCheck = fnCheckFileType();
        if (fnCheck > 0) {
            $("#file_type_msg").html("<span style='color:red'>Invalid File Type</span>");
            $("#magezine_image").css('border-color', 'red');
            intErrorCount = 1
        }
    }

    if (intErrorCount > 0) {
        return false;
    }

});


function fnGetDataFromAjax(strData, system_base_url)
{
    var base_url = window.location.origin;
    var intCount = 0;
    $.ajax({
        url:system_base_url+"index.php/magazine/fnCheckMagazineDetails",
        'type' : 'GET',
        async:false,
        'data' : {
            'magazine_id' :strData
        },
        success:function(result){
            if (result > 0) {
               intCount = result;
            }
        }
    });
    return intCount;
}

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

    return intCount;
}

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

    $("#magezine_image").focus(function(){
        $("#file_type_msg").html("");
    });
});