var userSessionId;

function showInterstFunc(uID){
    userSessionId = uID.id;

    var dataString = 'recepientId=' + userSessionId;
    var enteredMobileNumber = '';  
    var response = '';

    $.ajax(  // This checks first which kind of profile is this and it has mobile number or not etc.
    {
        type: "GET",
        url: "CheckProfileForShowInterest",
        data: dataString,
        async: false,
        error: function(errorData){
            response = errorData;
        },
        success : function(successData)
        {
            response = successData;
        },
        complete: function(){
            return response;
        }
    });

    if(response.responseText == 'normalProfile'){  // Opens the Show interest dialog box if true
     
        $('#progressbar').dialog('open');

        var dataString = 'recepientId=' + userSessionId;
      
        var response = '';     
        $.ajax({
            type: "GET",
            url: "ShowInterestAjax",
            data: dataString,
            async: false,
            error: function(errorData){
                response = errorData;
            },
            success : function(successData)
            {
                response = successData;
            },
            complete: function(){
                $("#progressbar").dialog('close');
                return response;
            }
        });

        if(response.responseText == 'failure'){
            alert("Oops - An internet connection Error has occured. Please Try again after some time.");
            window.location.reload()
            $(this).dialog('close');
            return true;
        }
        else if(response.responseText != ""){

            var matches = null;
            var strings = response.responseText;
            var showInterestLinkID = 'showInterestLink' + userSessionId;
            var statusPendingLinkID = 'statusPendingLink' + userSessionId;
            var sendMessageLinkID = 'sendMessageLink' + userSessionId;
            var sendMessageLinkBeforeSIID = 'sendMessageLinkBeforeSI' + userSessionId;

            matches =strings.match(/\d{8}/,strings);

            if(matches != null){
                alert("Thank you.... \n Your interest in this profile has been expressed to the parents/marriage bureau who have uploaded the profile. You may wish to contact the parents/marriage bureau direct on this mobile number: +91-" +  response.responseText + ". Wishing you all the success from FreeMatri.com");
                //window.location.reload()
                document.getElementById(showInterestLinkID).style.display='none';
                document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                document.getElementById(statusPendingLinkID).style.display='block';
                document.getElementById(sendMessageLinkID).style.display='block';

                $(this).dialog('close');
                return true;
            }
            else{
                alert("Thank you.... \n You have successfully shown interest in " + "'" + response.responseText + "'" + ". Please be patient until " + "'" + response.responseText + "'" + " accepts your interest!");
                //window.location.reload()
                document.getElementById(showInterestLinkID).style.display='none';
                document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                document.getElementById(statusPendingLinkID).style.display='block';
                document.getElementById(sendMessageLinkID).style.display='block';

                $(this).dialog('close');
                return true;
            }
        }

    }
    else if(response.responseText == 'profileWithoutMobile'){  // Opens the Enter Mobile number dialog box if true
        $('#dialogWarning').dialog('open');
    }
    else if(response.responseText == 'profileWithMobile'){  // Opens the Show interest dialog box if true
        $('#dialogWarningEachTime').dialog('open');
    }
    else if(response.responseText == 'aboveMaxInterestLimit'){
        alert("Sorry, you can show interest only 5 times a day!");
        return true;
    }
    else if(response.responseText == 'profileNotComplete'){
        alert("Since you have not completed your profile yet, you cannot initiate communication. Please complete your profile in \'My Profile\' Section.");
        return true;
    }
    else if(response.responseText == 'failureOppositeSex'){
        alert("You cannot show interest in members of the same gender.");
        return true;
    }
    else if(response.responseText == 'failure'){
        alert('Oops - An internet connection Error has occured. Please Try again after some time.');
        return true;
    }
}

$(function() {
    var mobileNumber = $("#mobileNumber"),
    allFields = $([]).add(mobileNumber),
    tips = $("#validateTipsMobile");

    function updateTips(t) {
        tips.text(t).effect("highlight",{},14500);
    }
    function checkLength(o,n,min,max) {
        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between "+min+" and "+max+".");
            return false;
        } else {
            return true;
        }
    }
    function checkRegexp(o,regexp,n) {
        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }
    function checkRegexpForIndianMobile(o,regexp,n) {
        if ( !( regexp.test( o.val() ) ) ) {           
            return false;
        } else {
            return true;
        }
    }
    $("#dialogGetMobile").dialog({  // Dialog box for getting user mobile number
        bgiframe: true,
        autoOpen: false,
        height: 310,
        modal: true,
        buttons: {
            'Submit': function() {
                var bValid = true;
                var bValidIndia = true;
                var bValidIndia2 = true;
                var bValidIndia3 = true;
                var indianMobile = false;
                allFields.removeClass('ui-state-error');
                tips.text("");

                bValid = bValid && checkLength(mobileNumber,"Mobile Number",10,15);
                //bValid = bValid && checkRegexp(mobileNumber,/^([9]{1})([123456789]{1})([0-9]{8})$/,"Mobile number may consist of 0-9.");
                bValid = bValid && checkRegexp(mobileNumber,/^[0-9]*$/,"Please ensure that your mobile number is in the numerical form consisting of digits from 0-9.");

                if(bValid){
                    bValidIndia = bValidIndia && checkRegexpForIndianMobile(mobileNumber,/^([8-9]{1})([0-9]{9})$/,"Please ensure that your mobile number is in the numerical form consisting of digits from 0-9.");

                    bValidIndia2 = bValidIndia2 && checkRegexpForIndianMobile(mobileNumber,/^([0]{1})([8-9]{1})([0-9]{9})$/,"Please ensure that your mobile number is in the numerical form consisting of digits from 0-9.");
                    bValidIndia3 = bValidIndia3 && checkRegexpForIndianMobile(mobileNumber,/^([9]{1})([1]{1})([8-9]{1})([0-9]{9})$/,"Please ensure that your mobile number is in the numerical form consisting of digits from 0-9.");

                    if(bValidIndia){
                        indianMobile = true;
                    }else if(bValidIndia2){
                        indianMobile = true;
                    }else if(bValidIndia3){
                        indianMobile = true;
                    }else{
                        indianMobile = false;
                    }

                    if (indianMobile) {
                        $('#progressbar').dialog('open');

                        var dataString = 'mobileNumber=' + $("#mobileNumber").val();
                        var response = '';

                        $.ajax({
                            type: "GET",
                            url: "SendSmsVerificationCode",
                            data: dataString,
                            async: false,
                            error: function(errorData){
                                response = errorData;
                            },
                            success : function(successData)
                            {
                                response = successData;
                            },
                            complete: function(){
                                $("#progressbar").dialog('close');
                                return response;
                            }
                        });
                        if(response.responseText == 'success'){
                            enteredMobileNumber = 'mobileNumber=' + $("#mobileNumber").val();
                            $('#dialogEnterCode').dialog('open');
                            $(this).dialog('close');
                            return true;
                        }
                        else if(response.responseText == 'failure'){
                            alert("Oops - An internet connection Error has occured. Please Try again after some time.");
                            window.location.reload()
                            $(this).dialog('close');
                            return true;
                        }
                    }
                    else {
                        $('#progressbar').dialog('open');

                        var dataString = 'mobileNumber=' + $("#mobileNumber").val() + '&recepientId=' + userSessionId;

                        var response = '';

                        $.ajax({
                            type: "GET",
                            url: "ShowInterestAjaxNRI",
                            data: dataString,
                            async: false,
                            error: function(errorData){
                                response = errorData;
                            },
                            success : function(successData)
                            {
                                response = successData;
                            },
                            complete: function(){
                                $("#progressbar").dialog('close');
                                return response;
                            }
                        });
                        if(response.responseText == 'failure' || response.responseText == ""){
                            alert("Oops - An internet connection Error has occured. Please Try again after some time.");
                            window.location.reload()
                            $(this).dialog('close');
                            return true;
                        }
                        else if(response.responseText != ""){
                            var showInterestLinkID = 'showInterestLink' + userSessionId;
                            var statusPendingLinkID = 'statusPendingLink' + userSessionId;
                            var sendMessageLinkID = 'sendMessageLink' + userSessionId;
                            var sendMessageLinkBeforeSIID = 'sendMessageLinkBeforeSI' + userSessionId;

                            alert("Thank you.... \n Your interest in this profile has been expressed to the parents/marriage bureau who have uploaded the profile. You may wish to contact the parents/marriage bureau direct on this mobile number: +91-" +  response.responseText + ". Wishing you all the success from FreeMatri.com");
                            //window.location.reload()
                            document.getElementById(showInterestLinkID).style.display='none';
                            document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                            document.getElementById(statusPendingLinkID).style.display='block';
                            document.getElementById(sendMessageLinkID).style.display='block';
                            $(this).dialog('close');
                            return true;
                        }
                    }
                }
              
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
        }
    });

    var tipsForCode = $("#validateTipsVerfiactionCode"),
    verificationCodeID = $("#verificationCodeID");

    function updateTipsForCode(t) {
        tipsForCode.text(t).effect("highlight",{},14500);
    }
    function checkLengthForCode(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTipsForCode("Length of " + n + " must be between "+min+" and "+max+".");
            return false;
        } else {
            return true;
        }
    }
    $("#dialogEnterCode").dialog({   // Dialog box for entering verification code to verify mobile number
        bgiframe: true,
        autoOpen: false,
        height: 250,
        modal: true,
        buttons: {
            'Submit': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');
                tips.text("");

                bValid = bValid && checkLengthForCode(verificationCodeID,"Verification Code",4,6);

                if (bValid) {
                    $('#progressbar').dialog('open');

                    var dataString = 'verificationCodeID=' + $("#verificationCodeID").val() + '&recepientId=' + userSessionId;
                    //alert (dataString);return false;
                    var response = '';

                    $.ajax({
                        type: "GET",
                        url: "GetMobilePopUp",
                        data: dataString,
                        async: false,
                        error: function(errorData){
                            response = errorData;
                        },
                        success : function(successData)
                        {
                            response = successData;
                        },
                        complete: function(){
                            $("#progressbar").dialog('close');
                            return response;
                        }
                    });

                    if(response.responseText == 'notMatch'){
                        var failureText = 'You have entered wrong code!';
                        updateTipsForCode(failureText);
                        return false;
                    }
                    else if(response.responseText == 'failure' || response.responseText == ""){
                        alert("Oops - An internet connection Error has occured. Please Try again after some time.");
                        window.location.reload()
                        $(this).dialog('close');
                        return true;
                    }
                    else if(response.responseText != ""){
                        var showInterestLinkID = 'showInterestLink' + userSessionId;
                        var statusPendingLinkID = 'statusPendingLink' + userSessionId;
                        var sendMessageLinkID = 'sendMessageLink' + userSessionId;
                        var sendMessageLinkBeforeSIID = 'sendMessageLinkBeforeSI' + userSessionId;

                        alert("Thank you.... \n Your interest in this profile has been expressed to the parents/marriage bureau who have uploaded the profile. You may wish to contact the parents/marriage bureau direct on this mobile number: +91-" +  response.responseText + ". Wishing you all the success from FreeMatri.com");
                        //window.location.reload()
                        document.getElementById(showInterestLinkID).style.display='none';
                        document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                        document.getElementById(statusPendingLinkID).style.display='block';
                        document.getElementById(sendMessageLinkID).style.display='block';
                        $(this).dialog('close');
                        return true;
                    }
                }
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
        }
    });
    $("#progressbar").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 80,
        modal: true
    });
    $("#dialogWarning").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 340,
        width: 426,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'Show Interest': function() {
                $('#dialogGetMobile').dialog('open');
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });
    $("#dialogWarningEachTime").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 340,
        width: 426,
        modal: true,
        overlay: {
            backgroundColor: '#000',
            opacity: 0.5
        },
        buttons: {
            'Show Interest': function() {

                $('#progressbar').dialog('open');

                var dataString = 'recepientId=' + userSessionId;
               
                var response = '';
                //$(this).dialog('close');
                $.ajax({
                    type: "GET",
                    url: "ShowInterestAjax",
                    data: dataString,
                    async: false,
                    error: function(errorData){
                        response = errorData;
                    },
                    success : function(successData)
                    {
                        response = successData;
                    },
                    complete: function(){
                        $("#progressbar").dialog('close');
                        return response;
                    }
                });

                if(response.responseText == 'failure'){
                    alert("Oops - An internet connection Error has occured. Please Try again after some time.");
                    window.location.reload()
                    $(this).dialog('close');
                    return true;
                }
                else if(response.responseText != ""){

                    var matches = null;
                    var strings = response.responseText;
                    var showInterestLinkID = 'showInterestLink' + userSessionId;
                    var statusPendingLinkID = 'statusPendingLink' + userSessionId;
                    var sendMessageLinkID = 'sendMessageLink' + userSessionId;
                    var sendMessageLinkBeforeSIID = 'sendMessageLinkBeforeSI' + userSessionId;

                    matches =strings.match(/\d{8}/,strings);

                    if(matches != null){
                        alert("Thank you.... \n Your interest in this profile has been expressed to the parents/marriage bureau who have uploaded the profile. You may wish to contact the parents/marriage bureau direct on this mobile number: +91-" +  response.responseText + ". Wishing you all the success from FreeMatri.com");
                        //window.location.reload()
                        document.getElementById(showInterestLinkID).style.display='none';
                        document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                        document.getElementById(statusPendingLinkID).style.display='block';
                        document.getElementById(sendMessageLinkID).style.display='block';

                        $(this).dialog('close');
                        return true;
                    }
                    else{
                        alert("Thank you.... \n You have successfully shown interest in " + "'" + response.responseText + "'" + ". Please be patient until " + "'" + response.responseText + "'" + " accepts your interest!");
                        //window.location.reload()
                        document.getElementById(showInterestLinkID).style.display='none';
                        document.getElementById(sendMessageLinkBeforeSIID).style.display='none';
                        document.getElementById(statusPendingLinkID).style.display='block';
                        document.getElementById(sendMessageLinkID).style.display='block';

                        $(this).dialog('close');
                        return true;
                    }
                }
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
                return false;
            }
        }
    });
});

function showMessageFunc(uId){
    var userId = uId.id;

    var dataString = 'recepientId=' + userId;   
    var response = '';

    $.ajax( 
    {
        type: "GET",
        url: "CheckProfileForSendMessage",
        data: dataString,
        async: false,
        error: function(errorData){
            response = errorData;
        },
        success : function(successData)
        {
            response = successData;
        },
        complete: function(){
            return response;
        }
    });

    if(response.responseText == 'failure'){
        alert("Oops - An internet connection Error has occured. Please Try again after some time.");
        window.location.reload()
        $(this).dialog('close');
        return true;
    }
    else if(response.responseText != ""){

        var matches = null;
        var strings = response.responseText;

        matches =strings.match(/\d{8}/,strings);

        if(matches != null){   // If output is mobile number then show popup
            alert("As this profile has been uploaded either by the parents or the marriage bureau, to contact them you can call at mobile number : +91-" +  strings + ". Wishing you all the success from FreeMatri.com");
        }
        else{       // If output is profile ID then show compose message page
            document.location= contextPath + '/faces/messages/composeMessage.jsp?userProfileID=' + strings;
        }
    }
}
