(function () {
    var jQuery;
    var serverFQDN = 'http://localhost/wid2/server';
    var timeoutId, options, container;
    var this_username;
    if (!window.BaltJS)
        window.BaltJS = {};
    BaltJS.Widget = function (opts) {
        options = opts;
        if (!options.buttonText) {
            options.buttonText = 'This text is configurable';
        }
        this_username = options.userName;
        container = '.widget-body';
    };
    function init() {
        if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.11.2') {
            console.log('we need to load jQuery');
            var script_tag = document.createElement('script');
            script_tag.setAttribute("type", "text/javascript");
            script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js");
            (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
            if (script_tag.attachEvent) {
                //console.log('oh cool, this is IE');
                script_tag.onreadystatechange = function () { // for IE
                    if (this.readyState == 'complete' || this.readyState == 'loaded') {
                        this.onreadystatechange = null;
                        scriptLoadHandler();
                    }
                };
            } else {
                script_tag.onload = scriptLoadHandler;
            }
        } else {
            jQuery = window.jQuery;
            console.log('jQuery already exists on page');
            main();
        }
    }

    function scriptLoadHandler() {
        jQuery = window.jQuery.noConflict();
        console.log('jQuery is now loaded');
        main();
    }

    function main() {
        jQuery(document).ready(function () {
            jQuery('head').append('<link href="' + serverFQDN + '/vendor/cleanslate.css" rel="stylesheet" type="text/css">');
            jQuery('head').append('<link href="' + serverFQDN + '/widget.css" rel="stylesheet" type="text/css">');
            jQuery.getScript(serverFQDN + '/vendor/json2.js');
//            var bootstrap_enabled = (typeof(jQuery.fn.modal) === 'undefined');
//            var bootstrap_enabled2 = (typeof(jQuery.fn.popover) ==='undifined');
//            
//            console.log(bootstrap_enabled + "  " + bootstrap_enabled2);
//            if (bootstrap_enabled && bootstrap_enabled2 ) {
//                jQuery('head').append('<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css">');
//                
//                jQuery.getScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js');
//            }


            jQuery('head').append('<link href="' + serverFQDN + '/slickModal/css/sm-minified.css" rel="stylesheet" type="text/css">');
//            jQuery('head').append('<script src="' + serverFQDN + '/slickModal/js/jquery.slick-modals.min.js" type="text/javascript"></script>');
            jQuery.getScript(serverFQDN + '/slickModal/js/jquery.slick-modals.min.js');


//            jQuery('head').append(' <link rel="stylesheet" href="' + serverFQDN + '/CCElite_Video_Player/css/elite.css" type="text/css" media="screen"/>');
//            jQuery('head').append(' <link rel="stylesheet" href="' + serverFQDN + '/CCElite_Video_Player/css/elite-font-awesome.css" type="text/css">');
//            jQuery('head').append(' <link rel="stylesheet" href="' + serverFQDN + '/CCElite_Video_Player/css/jquery.mCustomScrollbar.css" type="text/css">');
            
            jQuery('head').append(' <link href="' + serverFQDN + '/Elite-video-player/css/elite-font-awesome.min7888.css" rel="stylesheet" type="text/css"/>');
            jQuery('head').append('<link href="' + serverFQDN + '/Elite-video-player/css/elite.min7888.css" rel="stylesheet" type="text/css"/>');
            jQuery('head').append('<link href="' + serverFQDN + '/Elite-video-player/css/jquery.mCustomScrollbar.min7888.css" rel="stylesheet" type="text/css"/>');

            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/Playlist.min7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/THREEx.FullScreen.min7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/ZeroClipboard.min7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/embed7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/froogaloop.min7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/jquery.mCustomScrollbar.min7888.js" type="text/javascript"></script>');
            jQuery('head').append('<script src="' + serverFQDN + '/Elite-video-player/js/videoPlayer.min7888.js" type="text/javascript"></script>');

//            jQuery('body').append(' <script src="' + serverFQDN + '/CCElite_Video_Player/js/froogaloop.js" type="text/javascript"></script>');
//            jQuery('body').append(' <script src="' + serverFQDN + '/CCElite_Video_Player/js/jquery.mCustomScrollbar.js" type="text/javascript"></script> ');
//            jQuery('body').append(' <script src="' + serverFQDN + '/CCElite_Video_Player/js/THREEx.FullScreen.js"></script>');
//            jQuery('body').append(' <script src="' + serverFQDN + '/CCElite_Video_Player/js/videoPlayer.js" type="text/javascript"></script>');
//            jQuery('body').append(' <script src="' + serverFQDN + '/CCElite_Video_Player/js/Playlist.js" type="text/javascript"></script>');
//            jQuery('body').append(' <script type="text/javascript" src="' + serverFQDN + '/CCElite_Video_Player/js/ZeroClipboard.js"></script>');


            if (jQuery(container).size() === 0) {
                jQuery('body').append('<div class="widget-body"></div>');
                jQuery('.mjogger_wid').html('<h3>' + this_username + '</h3>').append('<button type="button" id="btnmo" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModalMediajogger">Visual Space</button><div class="openSlickModal-1 manualLabel">Reopen the popup</div> <div id="Elite_video_player2"></div>');
                //alert();
                jQuery('.mjogger_wid').append('<div id="popup-1" class="slickModal">' +
                        '<div class="window">' +
                        '<h1>You are almost set</h1>' +
                          
//                        '<iframe id="Elite_video_playeryoutube" allowfullscreen="1" title="YouTube video player" src="https://www.youtube.com/embed/?rel=1&amp;wmode=transparent&amp;controls=0&amp;enablejsapi=1&amp;iv_load_policy=3&amp;showinfo=0&amp;origin=http%3A%2F%2Flocalhost&amp;widgetid=1" width="100%" height="100%" frameborder="0"></iframe>'+
                        '<p><b>This is a blank, cluster free modal popup so you can put any HTML, iframe or other element inside it and get going fast.</b></p>' +
                        '<div class="closeModal demo-lb">Ok, got it!</div>' +
                        '<a href="../3. Documentation/index.html" class="docs" target="_blank">Open documentation</a>' +
                        '</div>');
            }


            jQuery(container).addClass('cleanslate');

            render();

            addModal();
            addplayer();
        });
    }

    function addModal() {
        jQuery("#popup-1").slickModals({
// Functionality
            popupType: "delayed",
            delayTime: 1000,
            exitTopDistance: 40,
            scrollTopDistance: 400,
            setCookie: true,
            cookieDays: 0,
            cookieTriggerClass: "setCookie-1",
            cookieName: "slickModal-1",
            // Overlay options
            overlayBg: true,
            overlayBgColor: "rgba(0,0,0,0.85)",
            overlayTransition: "ease",
            overlayTransitionSpeed: "0.4",
            // Background effects
            bgEffect: "none",
            blurBgRadius: "2px",
            scaleBgValue: "0.9",
            // Window options
            windowWidth: "900px",
            windowHeight: "600px",
            windowLocation: "center",
            windowTransition: "ease",
            windowTransitionSpeed: "0.4",
            windowTransitionEffect: "zoomIn",
            windowShadowOffsetX: "0",
            windowShadowOffsetY: "0",
            windowShadowBlurRadius: "20px",
            windowShadowSpreadRadius: "0",
            windowShadowColor: "rgba(0,0,0,0.3)",
            windowBackground: "rgba(255,255,255,1)",
            windowRadius: "12px",
            windowMargin: "30px",
            windowPadding: "30px",
            // Close and reopen button
            closeButton: "icon",
            reopenClass: "openSlickModal-1",
        });
    }

    function addplayer() {
        videoPlayer = jQuery("#Elite_video_player2").Video({//ALL PLUGIN OPTIONS
            instanceName: "Elite_video_player", //name of the player instance
            autohideControls: 3, //autohide HTML5 player controls
            hideControlsOnMouseOut: "No", //hide HTML5 player controls on mouse out of the player: "Yes","No"
            playerLayout: "fitToContainer", //Select player layout: "fitToContainer", "fixedSize", "fitToBrowser"
//            responsive: true, //this option will overwrite above videoPlayerWidth/videoPlayerHeight and set player to fit your div (parent) container: tru   
            videoPlayerWidth: 950, //fixed total player width
            videoPlayerHeight: 420, //fixed total player height
            lightBox: true, //lightbox mode :true/false
            lightBoxAutoplay: false, //autoplay video when lightbox opens: true/false
            lightBoxThumbnail: "http://placehold.it/200x60", //lightbox thumbnail image
            lightBoxThumbnailWidth: 200, //lightbox thumbnail image width
            lightBoxThumbnailHeight: 60, //lightbox thumbnail image height
            lightBoxCloseOnOutsideClick: true, //close lightbox when clicked outside of player area

            playlist: "Right playlist", //choose playlist type: "Right playlist", "Off"
            playlistScrollType: "light", //choose scrollbar type: "light","minimal","light-2","light-3","light-thick","light-thin","inset","inset-2","inset-3","rounded","rounded-dots","3d"
            playlistBehaviourOnPageload: "opened", //choose playlist behaviour when webpage loads: "closed", "opened" (not apply to Vimeo player)
            autoplay: false, //autoplay when webpage loads: true/false
            colorAccent: "#cc181e", //plugin colors accent (hexadecimal or RGB value - http://www.colorpicker.com/)
            vimeoColor: "00adef", //set "hexadecimal value", default vimeo color is "00adef"
            youtubeControls: "custom controls", //choose youtube player controls: "custom controls", "default controls"
            youtubeSkin: "dark", //youtube theme: light,dark
            youtubeColor: "red", //youtube color: red, white
            youtubeQuality: "default", //choose youtube quality: "small", "medium", "large", "hd720", "hd1080", "highres", "default"
            youtubeShowRelatedVideos: "Yes", //choose to show youtube related videos when video finish
            videoPlayerShadow: "effect1", //choose player shadow:  "effect1" , "effect2", "effect3", "effect4", "effect5", "effect6", "off"
            loadRandomVideoOnStart: "No", //choose to load random video when webpage loads: "Yes", "No"
            shuffle: "No", //choose to shuffle videos when playing one after another: "Yes", "No" (shuffle button enabled/disabled on start)
            posterImg: "images/preview_images/poster.jpg", //player poster image
            onFinish: "Play next video", //"Play next video","Restart video", "Stop video",
            nowPlayingText: "Yes", //enable disable now playing title: "Yes","No"
            fullscreen: "Fullscreen native", //choose fullscreen type: "Fullscreen native","Fullscreen browser"
            rightClickMenu: true, //enable/disable right click over player: true/false
            hideVideoSource: false, //option to hide self hosted video sources (to prevent users from download/steal your videos): true/false
            showAllControls: true, //enable/disable all HTML5 player controls: true/false
            allowSkipAd: true, //enable/disable "Skip advertisement" option: true/false
            infoShow: "Yes", //enable/disable info option: "Yes","No"
            shareShow: "Yes", //enable/disable all share options: "Yes","No"
            facebookShow: "Yes", //enable/disable facebook option individually: "Yes","No"
            twitterShow: "Yes", //enable/disable twitter option individually: "Yes","No"
            mailShow: "Yes", //enable/disable mail option individually: "Yes","No"
            facebookShareName: "Elite video player", //first parametar of facebook share in facebook feed dialog is title
            facebookShareLink: "http://codecanyon.net/item/elite-video-player-wordpress-plugin/10496434", //second parametar of facebook share in facebook feed dialog is link below title
            facebookShareDescription: "Elite Video Player is stunning, modern, responsive, fully customisable high-end video player for WordPress that support advertising and the most popular video platforms like YouTube, Vimeo or self-hosting videos (mp4).", //third parametar of facebook share in facebook feed dialog is description below link
            facebookSharePicture: "https://0.s3.envato.com/files/123866118/preview.jpg", //fourth parametar in facebook feed dialog is picture on left side
            twitterText: "Elite video player", //first parametar of twitter share in twitter feed dialog is text
            twitterLink: "http://codecanyon.net/item/elite-video-player-wordpress-plugin/10496434", //second parametar of twitter share in twitter feed dialog is link
            twitterHashtags: "wordpressvideoplayer", //third parametar of twitter share in twitter feed dialog is hashtag
            twitterVia: "Creative media", //fourth parametar of twitter share in twitter feed dialog is via (@)
            googlePlus: "http://codecanyon.net/item/elite-video-player-wordpress-plugin/10496434", //share link over Google +
            logoShow: "Yes", //"Yes","No"
            logoClickable: "Yes", //"Yes","No"
            logoPath: "images/logo/logo.png", //path to logo image
            logoGoToLink: "http://codecanyon.net/", //redirect to page when logo clicked
            logoPosition: "bottom-left", //choose logo position: "bottom-right","bottom-left"
            embedShow: "Yes", //enable/disable embed option: "Yes","No"
            embedCodeSrc: "www.yourwebsite.com/videoplayer/index.html", //path to your video player on server
            embedCodeW: "746", //embed player code width
            embedCodeH: "420", //embed player code height
            embedShareLink: "www.yourwebsite.com/videoplayer/index.html", //direct link to your site (or any other URL) you want to be "shared"
            youtubePlaylistID: "", //automatic youtube playlist ID (leave blank "" if you want to use manual playlist) LL4qbSRobYCjvwo4FCQFrJ4g
            youtubeChannelID: "", //automatic youtube channel ID (leave blank "" if you want to use manual playlist)

//manual playlist
            videos: [
                {
                    videoType: "youtube", //choose video type: "HTML5", "youtube", "vimeo"
                    title: "Youtube video", //video title
                    youtubeID: "LfTLc5JGFPc", //last part if the URL https://www.youtube.com/watch?v=LfTLc5JGFPc
                    vimeoID: "32707724", //last part of the URL http://vimeo.com/32707724
                    mp4: "http://player.pageflip.com.hr/videos/Pieces.mp4", //HTML5 video mp4 url
                    imageUrl: "", //display image instead of playing video
                    prerollAD: "no", //show pre-roll "yes","no"
                    prerollGotoLink: "http://codecanyon.net/", //pre-roll goto link
                    preroll_mp4: "http://player.pageflip.com.hr/videos/Short_Elegant_Logo_Reveal.mp4", //pre-roll video mp4 format
                    prerollSkipTimer: 5, //seconds when to show skip advertisement button
                    midrollAD: "no", //show mid-roll "yes","no"
                    midrollAD_displayTime: "00:10", //show mid-roll at any custom time in format "minutes:seconds" ("00:00")
                    midrollGotoLink: "http://codecanyon.net/", //mid-roll goto link
                    midroll_mp4: "http://creativeinteractivemedia.com/player/videos/Logo_Explode.mp4", //mid-roll video mp4 format
                    midrollSkipTimer: 5,
                    postrollAD: "yes", //show post-roll "yes","no"
                    postrollGotoLink: "http://codecanyon.net/", //post-roll goto link
                    postroll_mp4: "http://creativeinteractivemedia.com/player/videos/Logo_Light.mp4", //post-roll video mp4 format
                    postrollSkipTimer: 5,
                    popupImg: "images/preview_images/popup.jpg", //popup image URL
                    popupAdShow: "yes", //enable/disable popup image: "yes","no"
                    popupAdStartTime: "00:03", //time to show popup ad during playback
                    popupAdEndTime: "00:07", //time to hide popup ad during playback
                    popupAdGoToLink: "http://codecanyon.net/", //re-direct to URL when popup ad clicked
                    description: "Video description goes here.", //video description
                    thumbImg: "", //path to playlist thumbnail image
                    info: "Video info goes here.<br>This text can be <i>HTML formatted</i>, <a href='http://codecanyon.net/user/_zac_' target='_blank'><font color='008BFF'>find out more</font></a>.<br>You can disable this info window in player options. <br><br>Lorem ipsum dolor sit amet, eu pri dolores theophrastus. Posidonium vituperatoribus cu mel, cum feugiat nostrum sapientem ne. Vis ea summo persius, unum velit erant in eos, pri ut suas iriure euripidis. Ad augue expetendis sea. Ne usu saperet appetere honestatis, ne qui nulla debitis sententiae."    //video info
                }
            ]
        });

    }


    function render() {
        // build the widget
        var markup = '';
        markup = markup + '<input type="text" id="user_text" placeholder="type something"></input>';
        markup = markup + '<button>' + options.buttonText + '</button>';
        jQuery(container).append(markup);
        // handle events
        jQuery(container + ' button').click(handleClick);
        //jQuery('.mjogger_wid').on('click',getModal);

    }



    function handleClick() {
        jQuery(this).attr('disabled', 'disabled');
        // JSONP request to server
        jQuery.getJSON(serverFQDN + '/widget_submit.php?callback=?', {
            install_url: window.location.href,
            text: jQuery(container + ' #user_text').val()
        }, serverResponse);
    }

    function serverResponse(data) {
        jQuery(container + ' button').removeAttr('disabled');
        updateStatus(data.message + ' Your ip is ' + data.ip + '. Host site is ' + data.site + '. UA is ' + data.ua);
    }

    function updateStatus(msg) {
        if (jQuery(container + ' p.message').length === 0) {
            jQuery(container).append('<p class="message"></p>');
        }
        jQuery(container + ' p.message').html(msg);
    }

    init();

})();
