// Link view model
var linkVM = new function () {
    var self = this;
    
    self.recaptchaResponse = ko.observable('');

    self.load = function (linkRef, skipBind) {
        callAPI('publishing', 'GetNetworkLink', { linkRef: linkRef }, 'Get link', null,
            function (response) {
                if (response.result) {
                    ko.mapping.fromJS(response.link, {}, self);

                    if (!skipBind) 
                        // Apply bindings
                        ko.applyBindings(linkVM, $('#LinkDetails')[0]);
                }
                else
                    showMessageModal('View link', 'ERROR: ' + response.resultDetails, response.result);                
            }, null, null);
    }

    self.verify = function () {
        if ($('#frameAd').is(":visible") && $('#frameAd').height() >= 50)
        {
            callAPI('publishing', 'VerifyLinkClick', { linkRef: self.linkRef(), linkClickRef: $('#LinkClickRef')[0].value, recaptchaResponse: self.recaptchaResponse() }, 'Verify', 'Verifying',
            function (response) {
                if (response.result) 
                    window.location.href = response.linkURL;
                else 
                    showMessageModal('Verify failed', response.resultHtml, response.result);                                
            }, null,
            function () {
                grecaptcha.reset();
            });
        }
        else
            showMessageModal('Ad-block detected', 'Please disable your ad-blocking browser plugin/software or add this page to the exception list and then <a href="javascript:window.location.href=window.location.href" class="btn btn-default btn-xs">refresh the page</a>', false);
    };
};

function recaptchaCompleted(token)
{
    linkVM.recaptchaResponse(token);
}

$(document).ready(function () {
    //Load view models
    var linkRef = window.location.pathname.match(/.*\/([0-9][0-9A-Za-z]{3,5})/)[1];
    linkVM.load(linkRef);    
});
