/**
 * Libary for the playerand
 */

// This function will be called from the player
function ptvClickOut(id) {
    WebManagerAjaxPayTv.loadLoginLightBox(id);
}

var WebManagerAjaxPayTv = function() {

    //**************************
    // PUBLIC
    //**************************
    function loadLoginLightBox(contentid) {
        var windowLocation = window.location + '';

        // Use 'getRequestValue('redirectopen')' to prevent recursive redirects.
        if (!strStartsWith(windowLocation, 'https') && getRequestValue('redirectopen') == '') {
           var gotoUrl = $('#mainvideoplayerpage').attr('href');
           var gotoUrl = gotoUrl.replace();

           if (!strStartsWith(gotoUrl, 'https')) {
               gotoUrl = gotoUrl.replace('http' , 'https');
           }

           if (gotoUrl && typeof contentid != 'undefined') {
               if (gotoUrl.indexOf('?') > 0) {
                    window.location = gotoUrl + '&contentid=' + contentid + '&redirectopen=true';
                } else if (gotoUrl.indexOf('.htm') > 0) {
                   window.location = gotoUrl + '?contentid=' + contentid + '&redirectopen=true';
                } else {
                    window.location = gotoUrl + '/contentid=' + contentid + '/redirectopen=true';
                }
            }
        } else {

            $("#premium_dialog_contents").append('<div style="margin-top:180px;"><center><img src="' + $('#loadinglightboxurl').attr('value') + '"  alt="" /></center></div>');

            $("#premium_dialog_contents").load(getLoginUrl('?videoitem=' + contentid + '&openlightbox=true'), function() {
                $("#premium_dialog").jqmShow();
                $('#premium_dialog').jqmAddClose($('#closewindow, #closewindow_txt'));
                setupLoginDialogContent();
            });
        }
        return false;
    }

    function strStartsWith(str, prefix) {
        return str.indexOf(prefix) === 0;
    }

    function loadLightBox(url) {
        if (url != '') {
            $("#premium_dialog_contents").load(url, function() {
                $("#premium_dialog").jqmShow();
                setupLoginDialogContent();
            });
        }

        return false;
    }

    function init() {
        // Set local object vars here.
        _run();
    };

    // Setup the content for the dialog. After the load.
    function setupLoginDialogContent() {
        // Jarvis Ontwerpstudio
        $('#loginopenid').click(function(){
            $('.premium_content').hide();
            $('#content_openid').fadeIn(400);
        });

        $('#login_terugmain').click(function(){
            $('.premium_content').hide();
            $('#content_popupmain').fadeIn(400);
        });

        $('#premium_dialog').jqmAddClose($('#closewindow, #closewindow_txt'));
    }

    //**************************
    // PRIVATE
    //**************************

    function getLoginUrl(extra) {
        return $('#loginurl').attr("href") +  ((typeof extra != 'undefined') ? extra : '');
    }

    function getLoggedInNotEnoughRightsUrl(extra) {
        return $('#loggedinnotenoughrightsurl').attr("href") +  ((typeof extra != 'undefined') ? extra : '');
    }

    // Setup the PayTV components.
    function initGeneral() {
        // Auto trigger the lightbox.
        var windowLocation = window.location + '';

        if (windowLocation.indexOf('autoopen=true') > -1) {
            loadLightBox(getLoggedInNotEnoughRightsUrl());
        }

        if (windowLocation.indexOf('redirectopen=true') > -1) {
            var contentId = getRequestValue('contentid');

            if (contentId != '') {
                loadLoginLightBox(contentId);
            }
        }

        // FIXME: Bind a click event to open the lightbox. Normally the box will be openend by other call(from player).
        $('a.openloginbox').click(function() {
            loadLoginLightBox($(this).attr('id'));
        });

    }

    function getRequestValue(parameterName) {
        // Try get the value from the request parameters.
        var requestValue = getRequestParameter(parameterName);

        // Final try in the path.
        if (requestValue == '') {
            var href = window.location.href;

            if (href.indexOf(parameterName + '=') > -1) {
                var stripFirst = href.substring(href.indexOf(parameterName + '='));

                if (stripFirst.indexOf('/') > -1) {
                    requestValue = stripFirst.substring((parameterName.length + 1), stripFirst.indexOf('/'));
                } else {
                    requestValue = stripFirst.substring(parameterName.length + 1);
                }
            }
        }
        return requestValue;
    }

    // Initialize the login lightbox.
    function initLoginDialog() {
        // Initialize the logic dialog.

        $('#premium_dialog').jqm({
            toTop:true,
            modal:true,
            onHide: function(hash) {
                $("#premium_dialog_contents").empty();
                 hash.w.hide();
                 hash.o.remove();
            }
        });
    }

    function getRequestParameter( name ) {
        name = name.replace(/[\[]/,'\\\[').replace(/[\]]/,'\\\]');
        var regexS = '[\\?&]'+name+'=([^&#]*)';
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return '';
        else
        return results[1];
    }
    /**
     * Called by the close button.
     */
    function closeLoginDialog() {
        $('#premium_dialog').jqmHide();
    }

    //**************************
    // PRIVATE
    //**************************
    function _run() {
        initGeneral();
        initLoginDialog();
    }

    // Public methods and variables
    return{
        init:init,
        loadLoginLightBox:loadLoginLightBox,
        setupLoginDialogContent:setupLoginDialogContent
    }
}();


$(document).ready(function() {
    // Initialize the WebManagerAjaxPayTv directly when it is included
    WebManagerAjaxPayTv.init();
});


