<commit_before>
//alert("service_url="+kmc.vars.service_url +"\n host=" + kmc.vars.host + "\n cdn_host=" + kmc.vars.cdn_host + " \n flash_dir=" + kmc.vars.flash_dir);
// @todo:
//		* Must do / should do:
//			* Graphics:
//				* overlay
//				* replace inline styles with classes
//			* Implement embed code template from server
//			* logout() shouldn't have to location.href to '/index.php/kmc/' (should already be ok on prod)
// *		* Fix uiconf names ("Kaltura", jw playlist names) (Gonen)
//
//		* Maybe / not that important / takes too long - pushed to Blackeye:
//			* why is srvurl flashvar hardcoded to "api_v3/index.php" (why not from kconf.php)
//			* organize kmcSuccess
//			* remove openPlayer/ openPlaylist flashvars for 2.0.9
//			* move some jw code into own sub-object (doJw)
//			* memory profiling
//				* nullify preview players
//				* kill swf's - profiling
//			* understand setObjectToRemove and use or remove
//			* move cookie functions to kmc.utils
//			* get rid of legacy functions
//			* a few leftover @todo's inside code
//			* deactivate header on openning of flash modal (Eitan)
//			* In p&e, if mix, show only message box for jw (Yaron)
//			* Full copy to clipboard
//			* Flavors preview to display based on flavor size with logic for not exceeding available screen area
 
/* WResize: plugin for fixing the IE window resize bug (http://noteslog.com/) */
(function($){$.fn.wresize=function(f){version='1.1';wresize={fired:false,width:0};function resizeOnce(){if($.browser.msie){if(!wresize.fired){wresize.fired=true}else{var version=parseInt($.browser.version,10);wresize.fired=false;if(version<7){return false}else if(version==7){var width=$(window).width();if(width!=wresize.width){wresize.width=width;return false}}}}return true}function handleWResize(e){if(resizeOnce()){return f.apply(this,[e])}}this.each(function(){if(this==window){$(this).resize(handleWResize)}else{$(this).resize(f)}});return this}})(jQuery);

$(window).load(function(){
    kmc.utils.activateHeader();
    $(window).wresize(kmc.utils.resize);
    kmc.vars.isLoadedInterval = setInterval("kmc.utils.isModuleLoaded()",200);
});

/* kmc and kmc.vars defined in script block in kmc2success.php */

// For debug enable to true
kmc.vars.debug = false;
	
// kmc.vars.quickstart_guide = "/content/docs/pdf/KMC_Quick_Start_Guide__Butterfly.pdf#";
kmc.vars.quickstart_guide = "/content/docs/pdf/KMC3_Quick_Start_Guide.pdf#"; // cassiopea

kmc.log = function(str) {
    if(kmc.vars.debug) { console.log(str); }
};
	
kmc.functions = {
    expired : function() {
        // @todo: why no cookie killing ?
        window.location = kmc.vars.service_url + "/index.php/kmc/kmc" + location.hash; // @todo: shouldn't require '/index.php/kmc/'
    },
    doNothing : function() {
        return false;
    },
    closeEditor : function(is_modified) { // KSE
        if(is_modified) {
            var myConfirm = confirm("Exit without saving?\n\n - Click [OK] to close editor\n\n - Click [Cancel] to remain in editor\n\n");
            if(!myConfirm) {
                return;
            }
        }
        document.getElementById("flash_wrap").style.visibility = "visible";
        kalturaCloseModalBox();
    },
    saveEditor : function() { // KSE
        return;
    },
    openKcw : function(ks, conversion_profile) {
        conversion_profile = conversion_profile || "";

        // use wrap = 0 to indicate se should be open withou the html & form wrapper ????
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width: 700, height: 360 } );
        modal.innerHTML = '<div id="kcw"></div>';
        var flashvars = {
            host			: kmc.vars.host,
            cdnhost			: kmc.vars.cdn_host,
            userId			: kmc.vars.user_id,
            partnerid		: kmc.vars.partner_id,
            subPartnerId	: kmc.vars.subp_id,
            sessionId		: kmc.vars.ks,
            devFlag			: "true",
            entryId			: "-1",
            kshow_id		: "-1",
            terms_of_use	: kmc.vars.terms_of_use,
            close			: "kmc.functions.onCloseKcw",
            quick_edit		: 0, 		// "when opening from the KMC - don't add to the roughcut" ???
            kvar_conversionQuality : conversion_profile
        };

        var params = {
            allowscriptaccess: "always",
            allownetworking: "all",
            bgcolor: "#DBE3E9",
            quality: "high",
            //				wmode: "opaque" ,
            movie: kmc.vars.service_url + "/kcw/ui_conf_id/" + kmc.vars.kcw_uiconf
        };

        swfobject.embedSWF(params.movie,			// old note: 36201 - new CW with ability to pass params not ready for this version
        "kcw", "680", "400" , "9.0.0", false, flashvars , params);

        setObjectToRemove("kaltura_cw"); // ???
    },
    onCloseKcw : function() {
        kmc.utils.hideFlash();
        kalturaCloseModalBox();
        modal = null;
        kmc.vars.kcw_open = false;
        // nullify flash object inside div kcw
    },
    openChangePwd : function(email) {
        kmc.utils.secureIframe('password', { email: email } );
    },
    openChangeEmail : function(email) {
        kmc.utils.secureIframe('email', { email: email } );
    },
    openChangeName : function(fname, lname) {
        kmc.utils.secureIframe('name', { fname: fname, lname: lname } );
    }
};

kmc.utils = {
			
    activateHeader : function() {
        $("#user_links a").click(function(e) {
            var tab = (e.target.tagName == "A") ? e.target.id : $(e.target).parent().attr("id");

            switch(tab) {
                case "Quickstart Guide" :
                    this.href = kmc.vars.quickstart_guide;
                    return true;
                    break;
                case "Logout" :
                    kmc.utils.logout();
                    return false;
                    break;
                case "Support" :
                    kmc.utils.openSupport(this);
                    return false;
                    break;
                case "ChangePartner" :
                    kmc.utils.changePartner();
                    return false;
                    break;
                default :
                    return false;
            }
        });
    },
		
    openSupport : function(href) {
        kalturaCloseModalBox();
        var modal_width = $.browser.msie ? 543 : 519;
        var iframe_height = $.browser.msie ? 751 : ($.browser.safari ? 697 : 732);
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width : modal_width , height: 450 } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>Support Request</b></div> <div id="modal_content"><iframe id="support" src="' + href + '" scrolling="no" frameborder="0"' +
            'marginheight="0" marginwidth="0" height="' + iframe_height + '" width="519"></iframe></div></div>';
        $("#mbContent").addClass("new");
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });
        return false;
    },

    // merge multipile (unlimited) json object into one.  All arguments passed must be json object.
    // The first argument passed is the json object into which the others will be merged.
    mergeJson : function() {
        var i,
        args=arguments.length,
        primaryObject=arguments[0];
        for(var j=1; j<args ; j++) {
            var jsonObj=arguments[j];
            for(i in jsonObj) {
                primaryObject[i] = jsonObj[i];
            }
        }
        return primaryObject;
    },
    jsonToQuerystring : function(jsonObj,joiner) {
        var i,
        myString="";
        if(typeof joiner == "undefined")
        var joiner = "&";
        for(i in jsonObj) {
            myString += i + "=" + jsonObj[i] + joiner;
        }
        return myString;
    },
    logout : function() {
        var expiry = new Date("January 1, 1970"); // "Thu, 01-Jan-70 00:00:01 GMT";
        expiry = expiry.toGMTString();
        document.cookie = "pid=; expires=" + expiry + "; path=/";
        document.cookie = "subpid=; expires=" + expiry + "; path=/";
        document.cookie = "uid=; expires=" + expiry + "; path=/";
        document.cookie = "kmcks=; expires=" + expiry + "; path=/";
        document.cookie = "screen_name=; expires=" + expiry + "; path=/";
        document.cookie = "email=; expires=" + expiry + "; path=/";
        var state = kmc.mediator.readUrlHash();
        $.ajax({
            url: location.protocol + "//" + location.hostname + "/index.php/kmc/logout",
            type: "POST",
            data: { "ks": kmc.vars.ks },
            dataType: "json",
            complete: function() {
                window.location = kmc.vars.service_url + "/index.php/kmc/kmc#" + state.moduleName + "|" + state.subtab;
            }
        });
    },
    copyCode : function () {
        $("#copy_msg").show();
        setTimeout(function(){$("#copy_msg").hide(500);},1500);
        $(" textarea#embed_code").select();
    },
    resize : function() {
        var doc_height = $(document).height(),
        offset = $.browser.mozilla ? 37 : 74;
        doc_height = (doc_height-offset)+"px";
        $("#flash_wrap").height(doc_height);
        $("#server_wrap iframe").height(doc_height);
    },
    escapeQuotes : function(string) {
        string = string.replace(/"/g,"&Prime;");
        string = string.replace(/'/g,"&prime;");
        return string;
    },
    isModuleLoaded : function() {
        if($("#flash_wrap object").length || $("#flash_wrap embed").length) {
            kmc.utils.resize();
            //				clearInterval(flashMovieTimeout);
            clearInterval(kmc.vars.isLoadedInterval);
            kmc.vars.isLoadedInterval = null;
        }
    },
    debug : function() {
        try{
            console.info(" ks: ",kmc.vars.ks);
            console.info(" partner_id: ",kmc.vars.partner_id);
        }
        catch(err) {}
    },

    /*,
		cookies : {
			set		: function(){},
			get		: function(){},
			kill	: function(){}
		}*/
    //};
		
    hideFlash : function(hide) {

        if(hide) {
            if( $.browser.msie ) {
                // For IE only we're positioning outside of the screen
                $("#flash_wrap").css("margin-right","3333px");
            } else {
                // For other browsers we're just make it
                $("#flash_wrap").css("visibility","hidden");
            }
        } else {
            if( $.browser.msie ) {
                $("#flash_wrap").css("margin-right","0");
            } else {
                $("#flash_wrap").css("visibility","visible");
            }
        }
    },
		
    closeModal : function() {
        kalturaCloseModalBox();
        kmc.utils.hideFlash();
        return false;
    },
	
    //hide header function
    maskHeader : function(hide) {
        if(hide) {
            $("#mask").remove();
        }
        else {
            $("#kmcHeader").append('<div id="mask"></div>');
        }
    },
		
    createTabs : function(arr) {
        if(arr) {
            var module_url = kmc.vars.service_url + '/index.php/kmc/kmc4';
            var arrLen = arr.length;
            var tabsHTML = '';
            for( var i = 0; i < arrLen; i++ ) {
                tabsHTML += '<li><a id="'+ arr[i].module_name +'" rel="'+ arr[i].subtab +'" href="'+ module_url + '#' + arr[i].module_name +'|'+ arr[i].subtab +'"><span>' + arr[i].display_name + '</span></a></li>';
            }
				
            $('#hTabs').html(tabsHTML);
				
            $('#hTabs a').click(function(e) {
                var tab = (e.target.tagName == "A") ? e.target.id : $(e.target).parent().attr("id");
                var subtab = (e.target.tagName == "A") ? $(e.target).attr("rel") : $(e.target).parent().attr("rel");
					
                var go_to = { moduleName : tab, subtab : subtab };
                //alert($("#kcms")[0].id);
                $("#kcms")[0].gotoPage(go_to);
                return false;
					
            });
        } else {
            alert('Error geting tabs');
        }
    },
		
    setTab : function(module){
        $("#kmcHeader ul li a").removeClass("active");
        $("a#" + module).addClass("active");
    },
		
    showFlash : function() {
        $("#server_wrap").hide();
        $("#server_frame").removeAttr('src');
        $("#flash_wrap").css("visibility","visible");
        $("#server_wrap").css("margin-top", 0);
    },
		
    openIframe : function(url) {
        $("#flash_wrap").css("visibility","hidden");
        $("#server_frame").attr("src", url);
        $("#server_wrap").css("margin-top", "-"+ ($("#flash_wrap").height() + 2) +"px");
        $("#server_wrap").show();
    },
		
    secureIframe : function(action, fields) {
        // Set title
        var title;
        switch(action) {
            case "password":
                title = "Change Password";
                break;
            case "email":
                title = "Change Email Address";
                break;
                case "name":
                    title = "Edit Name";
                break;
        }
			
        // set url
        var url = kmc.vars.service_url + "/secure_form.php?action=" + action;
        // pass in the fields
        for(var i in fields) {
            var fld = (fields[i]) ? fields[i] : '';
            url += '&' + i + '=' + fld;
        }
        // change http to https
        url = url.replace("http", "https");
			
        // Pass the parent url for the postMessage to work
        url = url + '&parent=' + encodeURIComponent(document.location.href);
			
        var modal_width = 370;
        var modal_height = 160;
        var iframe_width = modal_width;
        if( $.browser.msie ) {
            modal_width = modal_width + 24;
        }
        kmc.utils.hideFlash(true);
        kalturaCloseModalBox();
        modal = kalturaInitModalBox ( null , { width : modal_width , height: modal_height } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>' + title + '</b></div> <div id="modal_content"><iframe id="sec_iframe" src="' + url + '" scrolling="no" frameborder="0"' +
            ' height="' + modal_height + '" width="' + iframe_width + '"></iframe></div></div>';
        $("#mbContent").addClass("new");
		 
        // setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
        // event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
        var from_domain = kmc.vars.service_url.replace("http", "https");
        XD.receiveMessage(function(message){
            if(message.data == "reload") {
                kmc.utils.closeModal();
                window.location.reload();
            } else {
                kmc.utils.closeModal();
            }
        }, from_domain);
			
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });

    },
		
    changePartner : function() {
			
        var modal_width = 300;
        var modal_height = 180;
        var size = 'width: ' + modal_width + 'px; height: ' + modal_height + 'px';
        var title = 'Change Account';
        var content = '<br />Please choose partner:<br /><br />';
        var pid = 0;
			
        var partners_count = kmc.vars.allowed_partners.length;
        for( var i=0; i < partners_count; i++ ) {
            pid = kmc.vars.allowed_partners[i].id;
            if( kmc.vars.partner_id == pid ) {
                var selected = ' checked="checked"';
                var bolded = ' style="font-weight: bold"';
            } else {
                var selected = '';
                var bolded = '';
            }
            content += '<input id="cp' + pid + '" type="radio" name="pid" value="' + pid + '" ' + selected + '/> &nbsp;';
            content += '<label for="cp' + pid + '"' + bolded + '>' + kmc.vars.allowed_partners[i].name + '</label><br />';
        }
        content += '<br /><div class="center"><input id="do_change_partner" type="button" value=" Go " style="width: 100px;" /></div>';
			
        kmc.utils.hideFlash(true);
        kalturaCloseModalBox();
        modal = kalturaInitModalBox ( null , { width : modal_width , height: modal_height } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>' + title + '</b></div> <div id="modal_content" style="' + size + '">' + content + '</div></div>';
        $("#mbContent").addClass("new");
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });
			
        $("#do_change_partner").click(function() {
            var pid = $('input[name=pid]:radio:checked').val();
            var url = '/index.php/kmc/extlogin?ks=' + kmc.vars.ks + '&partner_id=' + pid;
            //kmc.log(url);
            window.location.href = url;
        });
			
        return false;
    }
		
};

kmc.mediator =  {
    /*
		  Need to implement saveAndClose call to module before switching tabs via html click:
			- inside swf's, show confirm: Save your changes before exiting ? [Yes] [No] [Cancel]
				- Yes = save and return true to html js function (to continue with tab change)
				- No = return true to html js function (without saving)
				- Cancel = return false to html js function, thereby canceling tab change
			- currently saveandclose calls onTabChange (no need)
     */
    setState : function(go_to) { // go_to as json { module : module, subtab : subtab  }
        //			alert("setState("+go_to.module+","+go_to.subtab+")");
        if(!go_to) {
            //				alert("!go_to");
            go_to = kmc.vars.next_state; // dbl... checked elsewhere
            kmc.vars.next_state = null; // ???
        }
        if(go_to.subtab == "uploadKMC") {
            //				alert("open kcw");
            //				kmc.functions.openKcw();
            kmc.vars.kcw_open = true;
            //openCw(kmc.vars.ks, null); // null = conversion_quality
            go_to.subtab = "Upload";
        }
        if(go_to.subtab.toLowerCase() == "publish")
            go_to.subtab = "Playlists";
        if(!kmc.vars.kcw_open) { // ???
            //				alert("CloseModalBox");
            kalturaCloseModalBox();
        }
        //			alert("kmc.mediator.loadModule(" + go_to.module + "," + go_to.subtab + ")");
        kmc.mediator.setTab(go_to.module);
        //			alert("post setTab");
        kmc.mediator.writeUrlHash(go_to.module,go_to.subtab);
        //			alert("post writeUrlHash");
        //			if(navigator.userAgent.indexOf("Chrome") != -1) {
        ////				alert("chrome");
        //				setTimeout(kmc.mediator.loadModule(go_to.module,go_to.subtab),100);
        //				return;
        //			}
        //			else {
        kmc.mediator.loadModule(go_to.module,go_to.subtab);
        //			}
        //			alert("post loadModule");
    },
    loadModule : function(module,subtab) {
        //	alert("loadModule("+module+","+subtab+")");
        window.kmc_module = null;	// nullify swf object - @todo: check if works/ set correctly
        module = module.toLowerCase();
        if(module=="account")
            module = "settings";
        //			subtab = subtab.charAt(0).toUpperCase() + subtab.slice(1).toLowerCase();
        subtab = subtab.replace(/ /g,"%20");
        var module_url = {data : eval("kmc.modules." + module + ".swf_url")};
        //	alert("module_url="+module_url.data);
        var attributes = kmc.utils.mergeJson(kmc.modules.shared.attributes,module_url);
        var flashvars = kmc.utils.mergeJson(kmc.modules.shared.flashvars,eval("kmc.modules." + module + ".flashvars"),{ subNavTab : subtab });
        flashvars = { flashvars : kmc.utils.jsonToQuerystring(flashvars) };
        var params = kmc.utils.mergeJson(kmc.modules.shared.params,flashvars);
        //			params.wmode = (module == "reports") ? "window" : "opaque";
        //			if(module == "settings") {
        //					params.wmode = "opaque";
        //			}
        //			alert(params.wmode);
        //	alert("swfobject.createSWF("+attributes+", "+params+", "+kcms+")");
        window.kmc_module = swfobject.createSWF(attributes, params, "kcms");
        if(kmc.vars.kcw_open) {
            kmc.utils.hideFlash(true);
            kmc.functions.openKcw();
            kmc.vars.kcw_open = false;
        }
        //			alert($("#kcms"));
    },
    writeUrlHash : function(module,subtab){
        //	alert("writeUrlHash");
        //			if(module == "account")
        //				module = "Settings";
        location.hash = module + "|" + subtab;
        document.title = "KMC > " + module + ((subtab && subtab != "") ? " > " + subtab + " |" : "");
        //			document.title = "KMC > " + module.charAt(0).toUpperCase() + module.slice(1) + ((subtab && subtab != "") ? " > " + subtab + " |" : "");
    },
    readUrlHash : function() {
        var module = "dashboard", // @todo: change to kmc.vars.default_state.module ?
        subtab = "";
        try {
            var hash = location.hash.split("#")[1].split("|");
        }
        catch(err) {
            var nohash=true;
            //				err = null;
        }
        if(!nohash && hash[0]!="") {
            module = hash[0];
            subtab = hash[1];
            extra = {};
            if (hash[2])
            {
                var tmp = hash[2].split("&");
                for (var i = 0; i<tmp.length; i++)
                {
                    var tmp2 = tmp[i].split(":");
                    extra[tmp2[0]] = tmp2[1];
                }
            }
        }
        return { "moduleName" : module, "subtab" : subtab, "extra" : extra };
    },
    selectContent : function(uiconf_id,is_playlist) { // called by selectPlaylistContent which is caled from appstudio
        //			alert("selectContent("+uiconf_id+","+is_playlist+")");
        var subtab = is_playlist ? "playlists" : "manage";
        //			kmc.vars.current_uiconf = uiconf_id; // used by doPreviewEmbed
        kmc.vars.current_uiconf = { "uiconf_id" : uiconf_id , "is_playlist" : is_playlist }; // used by doPreviewEmbed
        kmc.mediator.setState( { module : "content", subtab : subtab } );
    }
};

kmc.preview_embed = {

    // called from p&e dropdown, from content.swf and from appstudio.swf
    doPreviewEmbed : function(id, name, description, previewOnly, is_playlist, uiconf_id, live_bitrates, has_mobile_flavors, html5_compatible) {
        kmc.log('doPreviewEmbed');
        kmc.log(arguments);
		
        // default value for html5_compatible
        html5_compatible = (html5_compatible) ? html5_compatible : false;
	html5_compatible = (previewOnly) ? false : html5_compatible;
		
        if(id != "multitab_playlist") {

            name = kmc.utils.escapeQuotes(name);
            description = kmc.utils.escapeQuotes(description); // @todo: move to "// JW" block

            if(kmc.vars.current_uiconf) { // set by kmc.mediator.selectContent called from appstudio's "select content" action
                if((is_playlist && kmc.vars.current_uiconf.is_playlist) || (!is_playlist && !kmc.vars.current_uiconf.is_playlist)) { // @todo: minor optimization possible
                    var uiconf_id = kmc.vars.current_uiconf.uiconf_id;
                    //alert("doPreviewEmbed says:\nkmc.vars.current_uiconf true -> uiconf_id = "+uiconf_id);
                }
                kmc.vars.current_uiconf = null;
            }

            if(!uiconf_id) { // get default uiconf_id (first one in list)
                var uiconf_id = is_playlist ? kmc.vars.playlists_list[0].id : kmc.vars.players_list[0].id;
                //alert(uiconf_id);
            }

            if(uiconf_id > 899 && uiconf_id < 1000) {
                kmc.vars.silverlight = true;
            }
            // JW
            else if(uiconf_id > 799 && uiconf_id < 900) {
                kmc.vars.jw = true,
                jw_license_html = '<strong>COMMERCIAL</strong>',
                jw_options_html = '',
                jw_nomix_box_html = kmc.preview_embed.jw.showNoMix(false,"check");

                if(kmc.vars.jw_swf == "non-commercial.swf") {
                    jw_license_html =   '<a href="http://creativecommons.org/licenses/by-nc-sa/3.0/" target="_blank" class="license tooltip"' +
                        'title="With this license your player will show a JW Player watermark.  You may NOT use the non-commercial' +
                        'JW Player on commercial sites such as: sites owned or operated by corporations, sites with advertisements,' +
                        'sites designed to promote a product, service or brand, etc.  If you are not sure whether you need to '+
                        'purchase a license, contact us.  You also may not use the AdSolution monetization plugin ' +
                        '(which lets you make money off your player).">NON-COMMERCIAL <img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" />' +
                        '</a>&nbsp;&bull;&nbsp;<a href="http://corp.kaltura.com/about/contact?subject=JW%20Player%20to%20commercial%20license&amp;' +
                        '&amp;pid=' + kmc.vars.partner_id + '&amp;name=' + kmc.vars.screen_name + '&amp;email=' + kmc.vars.email  + '" target="_blank" class="license tooltip" ' +
                        'title="Go to the Contact Us page and call us or fill in our Contact form and we\'ll call you (opens in new window/ tab).">Upgrade ' +
                        '<img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" /></a>';
                    var jw_license_ads_html = '<li>Requires <a href="http://corp.kaltura.com/about/contact?subject=JW%20Player%20to%20commercial%20license&amp;" ' +
                        'class="tooltip" title="With a Commercial license your player will not show the JW Player watermark and you will be ' +
                        'allowed to use the player on any site you want as well as use AdSolution (which lets you make money off your player)."' +
                        'target="_blank">Commercial license <img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" /></a></li>';
                }
                jw_options_html =	'<div class="label">License Type:</div>\n<div class="description">' + jw_license_html + '</div>\n' +
                    '<div class="label">AdSolution:</div><div class="description"> <input type="checkbox" id="AdSolution" ' +
                    'onclick="kmc.preview_embed.jw.adSolution()" onmousedown="kmc.vars.jw_chkbox_flag=true" /> Enable ads ' +
                    'in your videos.&nbsp; <a href="http://www.longtailvideo.com/referral.aspx?page=kaltura&ref=azbkefsfkqchorl" ' +
                    'target="_blank" class="tooltip" title="Go to the JW website to sign up for FREE or to learn more about ' +
                    'running in-stream ads in your player from Google AdSense for Video, ScanScout, YuMe and others. (opens ' +
                    'in new window/ tab)"> Free sign up... <img src="http://corp.kaltura.com/images/graphics/info.png" alt="' +
                    'show tooltip" /></a><br />\n <ul id="ads_notes">\n  <li>Channel Code: <input onblur="' +
                    'kmc.preview_embed.jw.adsChannel(this, \'' + id + '\', \'' + name + '\', \'' + description + '\', ' + (is_playlist || false) + ', \'' + uiconf_id + '\');" ' +
                    'type="text" id="adSolution_channel" value="" /> <button>Apply</button></li>\n' + (jw_license_ads_html || '') +
                    '\n </ul>\n </div>\n';
            } // END JW
        } // end !multitab_playlist

        var embed_code, preview_player,
        id_type = is_playlist ? "Playlist " + (id == "multitab_playlist" ? "Name" : "ID") : "Embedding",
        uiconf_details = kmc.preview_embed.getUiconfDetails(uiconf_id,is_playlist);
			
        name = (name) ? name : '';
        //			kmc.log("uiconf_details="+uiconf_details);
        if(kmc.vars.jw) {
            embed_code = kmc.preview_embed.jw.buildJWEmbed(id, name, description, is_playlist, uiconf_id);
            preview_player = embed_code.replace('flvclipper', 'flvclipper/ks/' + kmc.vars.ks);
        }
        else if(kmc.vars.silverlight) {
            embed_code = kmc.preview_embed.buildSilverlightEmbed(id, name, is_playlist, uiconf_id);
            preview_player = embed_code.replace('{KS}','ks=' + kmc.vars.ks);
            embed_code = embed_code.replace('{KS}','');
            embed_code = embed_code.replace("{ALT}", ((kmc.vars.whitelabel) ? "" : "<br/>" + kmc.preview_embed.embed_code_template.kaltura_links));
        }
        else {
            embed_code = kmc.preview_embed.buildKalturaEmbed(id, name, description, is_playlist, uiconf_id);
            preview_player = embed_code.replace('{FLAVOR}','ks=' + kmc.vars.ks + '&');
            embed_code = embed_code.replace('{FLAVOR}','');
        }
        var modal_html = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<a id="help" target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#contentSection118"></a>' + id_type +
            ': ' + name + '</div> <div id="modal_content">' +
            //							 ((typeof(live_bitrates) == "object") ? kmc.preview_embed.buildLiveBitrates(name,live_bitrates) : '') + // always return true because null is an object
        ((live_bitrates) ? kmc.preview_embed.buildLiveBitrates(name,live_bitrates) : '') +
            '<div id="player_wrap">' + preview_player + '</div>' +
            //							 ((id == "multitab_playlist") ? '' : kmc.preview_embed.buildSelect(id, name, description, is_playlist, uiconf_id)) +
        ((id == "multitab_playlist") ? '' : kmc.preview_embed.buildSelect(is_playlist, uiconf_id)) +
            (kmc.vars.jw ? jw_nomix_box_html : '') +
            (kmc.vars.jw ? jw_options_html : '') +
            ((kmc.vars.silverlight || live_bitrates) ? '' : kmc.preview_embed.buildRtmpOptions()) +
            ((html5_compatible) ? kmc.preview_embed.buildHTML5Option(id, kmc.vars.partner_id, uiconf_id, has_mobile_flavors) : '') +
            '<div class="embed_code_div"><div class="label">Embed Code:</div> <div class="right"><textarea id="embed_code" rows="5" cols=""' +
            // style="width:' + (parseInt(uiconf_details.width)-10) + 'px;"
        'readonly="true">' + embed_code + '</textarea></div><br class="clear" />' +
            '<div id="copy_msg">Press Ctrl+C to copy embed code (Command+C on Mac)</div><div class="center"><button id="select_code">' +
            '<span>Select Code</span></button></div></div></div></div>';
        //			alert(modal_html);
        kmc.vars.jw = false;
        kmc.vars.silverlight = false;

        kalturaCloseModalBox();

        kmc.utils.hideFlash(true);
			
        modal = kalturaInitModalBox ( null , { width : parseInt(uiconf_details.width) + 140 , height: parseInt(uiconf_details.height) + 200 } );
        modal.innerHTML = modal_html;
        $("#mbContent").addClass("new");
        // attach events here instead of writing them inline
        $("#embed_code, #select_code").click(function(){
            kmc.utils.copyCode();
        });
        $("#close").click(function(){
            kmc.utils.closeModal();
            return false;
        });
        $("#delivery_type").change(function(){
            kmc.vars.embed_code_delivery_type = this.value;
            kmc.preview_embed.doPreviewEmbed(id, name, description, previewOnly, is_playlist, uiconf_id, live_bitrates, has_mobile_flavors, html5_compatible);
        });
        $("#player_select").change(function(){
            kmc.preview_embed.doPreviewEmbed(id, name, description, previewOnly, is_playlist, this.value, live_bitrates, has_mobile_flavors, html5_compatible);
        });
			
        $("#html5_support").change(function(){
            var html5_support = ($(this).attr("checked")) ? true : false;
            var val = kmc.preview_embed.buildKalturaEmbed(id,name,description, is_playlist, uiconf_id, html5_support);
            $("#embed_code").val(val);
        });
			
        // show the embed code & enable the checkbox if its not a preview
        if (previewOnly==false) {
            $('.embed_code_div').show();
        }
        if(has_mobile_flavors) {
            $('#html5_support').attr('disabled', null);
        }
    }, // doPreviewEmbed

    buildLiveBitrates : function(name,live_bitrates) {
        //kmc.log('buildLiveBitrates');
        //kmc.log(arguments);
        var bitrates = "",
        len = live_bitrates.length,
        i;
        for(i=0;i<len;i++) {
            bitrates += live_bitrates[i].bitrate + " kbps, " + live_bitrates[i].width + " x " + live_bitrates[i].height + "<br />";
        }
        var lbr_data = 	'<dl style="margin: 0 0 15px">' + '<dt>Name:</dt><dd>' + name + '</dd>' +
            '<dt>Bitrates:</dt><dd>' + bitrates + '</dd></dl>';
        return lbr_data;
    },

    buildSilverlightEmbed : function(id, name, is_playlist, uiconf_id) {
        var uiconf_details = kmc.preview_embed.getUiconfDetails(uiconf_id,is_playlist),
        cache_st = kmc.preview_embed.setCacheStartTime(),
        embed_code = kmc.preview_embed.embed_code_template.silverlight;
        embed_code = embed_code.replace("{WIDTH}",uiconf_details.width);
        embed_code = embed_code.replace("{HEIGHT}",uiconf_details.height);
        embed_code = embed_code.replace("{HOST}",kmc.vars.host);
        embed_code = embed_code.replace("{CACHE_ST}",cache_st);
        embed_code = embed_code.replace("{VER}",uiconf_details.swfUrlVersion); // sl
        embed_code = embed_code.replace("{PARTNER_ID}",kmc.vars.partner_id);
        //			embed_code = embed_code.replace("{CDN_HOST}",kmc.vars.cdn_host); // sl
        embed_code = embed_code.replace("{UICONF_ID}",uiconf_id);
        embed_code = embed_code.replace(/{SILVERLIGHT}/gi,uiconf_details.minRuntimeVersion);
        embed_code = embed_code.replace("{INIT_PARAMS}",(is_playlist ? "playlist_id" : "entry_id"));
        embed_code = embed_code.replace("{ENTRY_ID}", id);
        return embed_code;
    },
    buildRtmpOptions : function() {
        var selected = ' selected="selected"';
        var delivery_type = kmc.vars.embed_code_delivery_type || "http";
        var html = '<div id="rtmp" class="label">Select Delivery Type:</div> <div class="right"><select id="delivery_type">';
        var options = '<option value="http"' + ((delivery_type == "http") ? selected : "") + '>Progressive Download (HTTP)&nbsp;</option>' +
            '<option value="rtmp"' + ((delivery_type == "rtmp") ? selected : "") + '>Adaptive Streaming (RTMP)&nbsp;</option>';
        if(!kmc.vars.hide_akamai_hd_network) {
            options += '<option value="akamai"' + ((delivery_type == "akamai") ? selected : "") + '>Akamai HD Network &nbsp;</option>';
        }
        html += options + '</select></div><br /><div class="note">Adaptive Streaming automatically adjusts to the viewer\'s bandwidth,' +
            'while Progressive Download allows buffering of the content. <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#deliveryType">Read more</a></div><br />';
        return html;
    },
		
    buildHTML5Option : function(entry_id, partner_id, uiconf_id, has_mobile_flavors) {
        kmc.log('buildHTML5Option');
        kmc.log(arguments);
			
        var long_url = kmc.vars.service_url + '/index.php/kmc/preview/partner_id/' + partner_id + '/entry_id/' + entry_id + '/uiconf_id/' + uiconf_id;
        kmc.client.getShortURL(long_url);
			
        var description = '<div class="note red">This video does not have video flavors compatible with IPhone & IPad. <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#html5Support">Read more</a></div>';
        if(has_mobile_flavors) {
            description = '<div class="note">If you enable the HTML5 player, the viewer device will be automatically detected.' +
                ' <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#html5Support">Read more</a>' +
                '<br class"clear" />View player outside KMC: <span class="preview_url"><img src="/lib/images/kmc/url_loader.gif" alt="loading..." /> Updating Short URL...</span></div>';
        }
        var html = '<div class="label checkbox"><input id="html5_support" type="checkbox" disabled="disabled" /> <label for="html5_support">Support iPhone' +
            ' &amp; iPad with HTML5</label></div><br />' + description + '<br />';
        return html;
    },

    // for content|Manage->drilldown->flavors->preview
    // flavor_details = json:
    doFlavorPreview : function(entry_id, entry_name, flavor_details) {
        //			kmc.log(flavor_details);
        //			alert("doFlavorPreview(entry_id="+entry_id+", entry_name="+entry_name+", flavor_details logged)");
        entry_name = kmc.utils.escapeQuotes(entry_name);
        //			var flavor_asset_name = kmc.utils.escapeQuotes(flavor_details.flavor_name) || "unknown";
        kalturaCloseModalBox();
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width : parseInt(kmc.vars.default_kdp.width) + 20 , height: parseInt(kmc.vars.default_kdp.height) + 10 } );
        $("#mbContent").addClass("new");
        var player_code = kmc.preview_embed.buildKalturaEmbed(entry_id,entry_name,null,false,kmc.vars.default_kdp);<commit_msg>added delivery type to preview url<commit_after>
//alert("service_url="+kmc.vars.service_url +"\n host=" + kmc.vars.host + "\n cdn_host=" + kmc.vars.cdn_host + " \n flash_dir=" + kmc.vars.flash_dir);
// @todo:
//		* Must do / should do:
//			* Graphics:
//				* overlay
//				* replace inline styles with classes
//			* Implement embed code template from server
//			* logout() shouldn't have to location.href to '/index.php/kmc/' (should already be ok on prod)
// *		* Fix uiconf names ("Kaltura", jw playlist names) (Gonen)
//
//		* Maybe / not that important / takes too long - pushed to Blackeye:
//			* why is srvurl flashvar hardcoded to "api_v3/index.php" (why not from kconf.php)
//			* organize kmcSuccess
//			* remove openPlayer/ openPlaylist flashvars for 2.0.9
//			* move some jw code into own sub-object (doJw)
//			* memory profiling
//				* nullify preview players
//				* kill swf's - profiling
//			* understand setObjectToRemove and use or remove
//			* move cookie functions to kmc.utils
//			* get rid of legacy functions
//			* a few leftover @todo's inside code
//			* deactivate header on openning of flash modal (Eitan)
//			* In p&e, if mix, show only message box for jw (Yaron)
//			* Full copy to clipboard
//			* Flavors preview to display based on flavor size with logic for not exceeding available screen area
 
/* WResize: plugin for fixing the IE window resize bug (http://noteslog.com/) */
(function($){$.fn.wresize=function(f){version='1.1';wresize={fired:false,width:0};function resizeOnce(){if($.browser.msie){if(!wresize.fired){wresize.fired=true}else{var version=parseInt($.browser.version,10);wresize.fired=false;if(version<7){return false}else if(version==7){var width=$(window).width();if(width!=wresize.width){wresize.width=width;return false}}}}return true}function handleWResize(e){if(resizeOnce()){return f.apply(this,[e])}}this.each(function(){if(this==window){$(this).resize(handleWResize)}else{$(this).resize(f)}});return this}})(jQuery);

$(window).load(function(){
    kmc.utils.activateHeader();
    $(window).wresize(kmc.utils.resize);
    kmc.vars.isLoadedInterval = setInterval("kmc.utils.isModuleLoaded()",200);
});

/* kmc and kmc.vars defined in script block in kmc2success.php */

// For debug enable to true
kmc.vars.debug = false;
	
// kmc.vars.quickstart_guide = "/content/docs/pdf/KMC_Quick_Start_Guide__Butterfly.pdf#";
kmc.vars.quickstart_guide = "/content/docs/pdf/KMC3_Quick_Start_Guide.pdf#"; // cassiopea

kmc.log = function(str) {
    if(kmc.vars.debug) { console.log(str); }
};
	
kmc.functions = {
    expired : function() {
        // @todo: why no cookie killing ?
        window.location = kmc.vars.service_url + "/index.php/kmc/kmc" + location.hash; // @todo: shouldn't require '/index.php/kmc/'
    },
    doNothing : function() {
        return false;
    },
    closeEditor : function(is_modified) { // KSE
        if(is_modified) {
            var myConfirm = confirm("Exit without saving?\n\n - Click [OK] to close editor\n\n - Click [Cancel] to remain in editor\n\n");
            if(!myConfirm) {
                return;
            }
        }
        document.getElementById("flash_wrap").style.visibility = "visible";
        kalturaCloseModalBox();
    },
    saveEditor : function() { // KSE
        return;
    },
    openKcw : function(ks, conversion_profile) {
        conversion_profile = conversion_profile || "";

        // use wrap = 0 to indicate se should be open withou the html & form wrapper ????
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width: 700, height: 360 } );
        modal.innerHTML = '<div id="kcw"></div>';
        var flashvars = {
            host			: kmc.vars.host,
            cdnhost			: kmc.vars.cdn_host,
            userId			: kmc.vars.user_id,
            partnerid		: kmc.vars.partner_id,
            subPartnerId	: kmc.vars.subp_id,
            sessionId		: kmc.vars.ks,
            devFlag			: "true",
            entryId			: "-1",
            kshow_id		: "-1",
            terms_of_use	: kmc.vars.terms_of_use,
            close			: "kmc.functions.onCloseKcw",
            quick_edit		: 0, 		// "when opening from the KMC - don't add to the roughcut" ???
            kvar_conversionQuality : conversion_profile
        };

        var params = {
            allowscriptaccess: "always",
            allownetworking: "all",
            bgcolor: "#DBE3E9",
            quality: "high",
            //				wmode: "opaque" ,
            movie: kmc.vars.service_url + "/kcw/ui_conf_id/" + kmc.vars.kcw_uiconf
        };

        swfobject.embedSWF(params.movie,			// old note: 36201 - new CW with ability to pass params not ready for this version
        "kcw", "680", "400" , "9.0.0", false, flashvars , params);

        setObjectToRemove("kaltura_cw"); // ???
    },
    onCloseKcw : function() {
        kmc.utils.hideFlash();
        kalturaCloseModalBox();
        modal = null;
        kmc.vars.kcw_open = false;
        // nullify flash object inside div kcw
    },
    openChangePwd : function(email) {
        kmc.utils.secureIframe('password', { email: email } );
    },
    openChangeEmail : function(email) {
        kmc.utils.secureIframe('email', { email: email } );
    },
    openChangeName : function(fname, lname) {
        kmc.utils.secureIframe('name', { fname: fname, lname: lname } );
    }
};

kmc.utils = {
			
    activateHeader : function() {
        $("#user_links a").click(function(e) {
            var tab = (e.target.tagName == "A") ? e.target.id : $(e.target).parent().attr("id");

            switch(tab) {
                case "Quickstart Guide" :
                    this.href = kmc.vars.quickstart_guide;
                    return true;
                    break;
                case "Logout" :
                    kmc.utils.logout();
                    return false;
                    break;
                case "Support" :
                    kmc.utils.openSupport(this);
                    return false;
                    break;
                case "ChangePartner" :
                    kmc.utils.changePartner();
                    return false;
                    break;
                default :
                    return false;
            }
        });
    },
		
    openSupport : function(href) {
        kalturaCloseModalBox();
        var modal_width = $.browser.msie ? 543 : 519;
        var iframe_height = $.browser.msie ? 751 : ($.browser.safari ? 697 : 732);
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width : modal_width , height: 450 } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>Support Request</b></div> <div id="modal_content"><iframe id="support" src="' + href + '" scrolling="no" frameborder="0"' +
            'marginheight="0" marginwidth="0" height="' + iframe_height + '" width="519"></iframe></div></div>';
        $("#mbContent").addClass("new");
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });
        return false;
    },

    // merge multipile (unlimited) json object into one.  All arguments passed must be json object.
    // The first argument passed is the json object into which the others will be merged.
    mergeJson : function() {
        var i,
        args=arguments.length,
        primaryObject=arguments[0];
        for(var j=1; j<args ; j++) {
            var jsonObj=arguments[j];
            for(i in jsonObj) {
                primaryObject[i] = jsonObj[i];
            }
        }
        return primaryObject;
    },
    jsonToQuerystring : function(jsonObj,joiner) {
        var i,
        myString="";
        if(typeof joiner == "undefined")
        var joiner = "&";
        for(i in jsonObj) {
            myString += i + "=" + jsonObj[i] + joiner;
        }
        return myString;
    },
    logout : function() {
        var expiry = new Date("January 1, 1970"); // "Thu, 01-Jan-70 00:00:01 GMT";
        expiry = expiry.toGMTString();
        document.cookie = "pid=; expires=" + expiry + "; path=/";
        document.cookie = "subpid=; expires=" + expiry + "; path=/";
        document.cookie = "uid=; expires=" + expiry + "; path=/";
        document.cookie = "kmcks=; expires=" + expiry + "; path=/";
        document.cookie = "screen_name=; expires=" + expiry + "; path=/";
        document.cookie = "email=; expires=" + expiry + "; path=/";
        var state = kmc.mediator.readUrlHash();
        $.ajax({
            url: location.protocol + "//" + location.hostname + "/index.php/kmc/logout",
            type: "POST",
            data: { "ks": kmc.vars.ks },
            dataType: "json",
            complete: function() {
                window.location = kmc.vars.service_url + "/index.php/kmc/kmc#" + state.moduleName + "|" + state.subtab;
            }
        });
    },
    copyCode : function () {
        $("#copy_msg").show();
        setTimeout(function(){$("#copy_msg").hide(500);},1500);
        $(" textarea#embed_code").select();
    },
    resize : function() {
        var doc_height = $(document).height(),
        offset = $.browser.mozilla ? 37 : 74;
        doc_height = (doc_height-offset)+"px";
        $("#flash_wrap").height(doc_height);
        $("#server_wrap iframe").height(doc_height);
    },
    escapeQuotes : function(string) {
        string = string.replace(/"/g,"&Prime;");
        string = string.replace(/'/g,"&prime;");
        return string;
    },
    isModuleLoaded : function() {
        if($("#flash_wrap object").length || $("#flash_wrap embed").length) {
            kmc.utils.resize();
            //				clearInterval(flashMovieTimeout);
            clearInterval(kmc.vars.isLoadedInterval);
            kmc.vars.isLoadedInterval = null;
        }
    },
    debug : function() {
        try{
            console.info(" ks: ",kmc.vars.ks);
            console.info(" partner_id: ",kmc.vars.partner_id);
        }
        catch(err) {}
    },

    /*,
		cookies : {
			set		: function(){},
			get		: function(){},
			kill	: function(){}
		}*/
    //};
		
    hideFlash : function(hide) {

        if(hide) {
            if( $.browser.msie ) {
                // For IE only we're positioning outside of the screen
                $("#flash_wrap").css("margin-right","3333px");
            } else {
                // For other browsers we're just make it
                $("#flash_wrap").css("visibility","hidden");
            }
        } else {
            if( $.browser.msie ) {
                $("#flash_wrap").css("margin-right","0");
            } else {
                $("#flash_wrap").css("visibility","visible");
            }
        }
    },
		
    closeModal : function() {
        kalturaCloseModalBox();
        kmc.utils.hideFlash();
        return false;
    },
	
    //hide header function
    maskHeader : function(hide) {
        if(hide) {
            $("#mask").remove();
        }
        else {
            $("#kmcHeader").append('<div id="mask"></div>');
        }
    },
		
    createTabs : function(arr) {
        if(arr) {
            var module_url = kmc.vars.service_url + '/index.php/kmc/kmc4';
            var arrLen = arr.length;
            var tabsHTML = '';
            for( var i = 0; i < arrLen; i++ ) {
                tabsHTML += '<li><a id="'+ arr[i].module_name +'" rel="'+ arr[i].subtab +'" href="'+ module_url + '#' + arr[i].module_name +'|'+ arr[i].subtab +'"><span>' + arr[i].display_name + '</span></a></li>';
            }
				
            $('#hTabs').html(tabsHTML);
				
            $('#hTabs a').click(function(e) {
                var tab = (e.target.tagName == "A") ? e.target.id : $(e.target).parent().attr("id");
                var subtab = (e.target.tagName == "A") ? $(e.target).attr("rel") : $(e.target).parent().attr("rel");
					
                var go_to = { moduleName : tab, subtab : subtab };
                //alert($("#kcms")[0].id);
                $("#kcms")[0].gotoPage(go_to);
                return false;
					
            });
        } else {
            alert('Error geting tabs');
        }
    },
		
    setTab : function(module){
        $("#kmcHeader ul li a").removeClass("active");
        $("a#" + module).addClass("active");
    },
		
    showFlash : function() {
        $("#server_wrap").hide();
        $("#server_frame").removeAttr('src');
        $("#flash_wrap").css("visibility","visible");
        $("#server_wrap").css("margin-top", 0);
    },
		
    openIframe : function(url) {
        $("#flash_wrap").css("visibility","hidden");
        $("#server_frame").attr("src", url);
        $("#server_wrap").css("margin-top", "-"+ ($("#flash_wrap").height() + 2) +"px");
        $("#server_wrap").show();
    },
		
    secureIframe : function(action, fields) {
        // Set title
        var title;
        switch(action) {
            case "password":
                title = "Change Password";
                break;
            case "email":
                title = "Change Email Address";
                break;
                case "name":
                    title = "Edit Name";
                break;
        }
			
        // set url
        var url = kmc.vars.service_url + "/secure_form.php?action=" + action;
        // pass in the fields
        for(var i in fields) {
            var fld = (fields[i]) ? fields[i] : '';
            url += '&' + i + '=' + fld;
        }
        // change http to https
        url = url.replace("http", "https");
			
        // Pass the parent url for the postMessage to work
        url = url + '&parent=' + encodeURIComponent(document.location.href);
			
        var modal_width = 370;
        var modal_height = 160;
        var iframe_width = modal_width;
        if( $.browser.msie ) {
            modal_width = modal_width + 24;
        }
        kmc.utils.hideFlash(true);
        kalturaCloseModalBox();
        modal = kalturaInitModalBox ( null , { width : modal_width , height: modal_height } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>' + title + '</b></div> <div id="modal_content"><iframe id="sec_iframe" src="' + url + '" scrolling="no" frameborder="0"' +
            ' height="' + modal_height + '" width="' + iframe_width + '"></iframe></div></div>';
        $("#mbContent").addClass("new");
		 
        // setup a callback to handle the dispatched MessageEvent. if window.postMessage is supported the passed
        // event will have .data, .origin and .source properties. otherwise, it will only have the .data property.
        var from_domain = kmc.vars.service_url.replace("http", "https");
        XD.receiveMessage(function(message){
            if(message.data == "reload") {
                kmc.utils.closeModal();
                window.location.reload();
            } else {
                kmc.utils.closeModal();
            }
        }, from_domain);
			
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });

    },
		
    changePartner : function() {
			
        var modal_width = 300;
        var modal_height = 180;
        var size = 'width: ' + modal_width + 'px; height: ' + modal_height + 'px';
        var title = 'Change Account';
        var content = '<br />Please choose partner:<br /><br />';
        var pid = 0;
			
        var partners_count = kmc.vars.allowed_partners.length;
        for( var i=0; i < partners_count; i++ ) {
            pid = kmc.vars.allowed_partners[i].id;
            if( kmc.vars.partner_id == pid ) {
                var selected = ' checked="checked"';
                var bolded = ' style="font-weight: bold"';
            } else {
                var selected = '';
                var bolded = '';
            }
            content += '<input id="cp' + pid + '" type="radio" name="pid" value="' + pid + '" ' + selected + '/> &nbsp;';
            content += '<label for="cp' + pid + '"' + bolded + '>' + kmc.vars.allowed_partners[i].name + '</label><br />';
        }
        content += '<br /><div class="center"><input id="do_change_partner" type="button" value=" Go " style="width: 100px;" /></div>';
			
        kmc.utils.hideFlash(true);
        kalturaCloseModalBox();
        modal = kalturaInitModalBox ( null , { width : modal_width , height: modal_height } );
        modal.innerHTML = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<b>' + title + '</b></div> <div id="modal_content" style="' + size + '">' + content + '</div></div>';
        $("#mbContent").addClass("new");
        $("#close").click(function() {
            kmc.utils.closeModal();
            return false;
        });
			
        $("#do_change_partner").click(function() {
            var pid = $('input[name=pid]:radio:checked').val();
            var url = '/index.php/kmc/extlogin?ks=' + kmc.vars.ks + '&partner_id=' + pid;
            //kmc.log(url);
            window.location.href = url;
        });
			
        return false;
    }
		
};

kmc.mediator =  {
    /*
		  Need to implement saveAndClose call to module before switching tabs via html click:
			- inside swf's, show confirm: Save your changes before exiting ? [Yes] [No] [Cancel]
				- Yes = save and return true to html js function (to continue with tab change)
				- No = return true to html js function (without saving)
				- Cancel = return false to html js function, thereby canceling tab change
			- currently saveandclose calls onTabChange (no need)
     */
    setState : function(go_to) { // go_to as json { module : module, subtab : subtab  }
        //			alert("setState("+go_to.module+","+go_to.subtab+")");
        if(!go_to) {
            //				alert("!go_to");
            go_to = kmc.vars.next_state; // dbl... checked elsewhere
            kmc.vars.next_state = null; // ???
        }
        if(go_to.subtab == "uploadKMC") {
            //				alert("open kcw");
            //				kmc.functions.openKcw();
            kmc.vars.kcw_open = true;
            //openCw(kmc.vars.ks, null); // null = conversion_quality
            go_to.subtab = "Upload";
        }
        if(go_to.subtab.toLowerCase() == "publish")
            go_to.subtab = "Playlists";
        if(!kmc.vars.kcw_open) { // ???
            //				alert("CloseModalBox");
            kalturaCloseModalBox();
        }
        //			alert("kmc.mediator.loadModule(" + go_to.module + "," + go_to.subtab + ")");
        kmc.mediator.setTab(go_to.module);
        //			alert("post setTab");
        kmc.mediator.writeUrlHash(go_to.module,go_to.subtab);
        //			alert("post writeUrlHash");
        //			if(navigator.userAgent.indexOf("Chrome") != -1) {
        ////				alert("chrome");
        //				setTimeout(kmc.mediator.loadModule(go_to.module,go_to.subtab),100);
        //				return;
        //			}
        //			else {
        kmc.mediator.loadModule(go_to.module,go_to.subtab);
        //			}
        //			alert("post loadModule");
    },
    loadModule : function(module,subtab) {
        //	alert("loadModule("+module+","+subtab+")");
        window.kmc_module = null;	// nullify swf object - @todo: check if works/ set correctly
        module = module.toLowerCase();
        if(module=="account")
            module = "settings";
        //			subtab = subtab.charAt(0).toUpperCase() + subtab.slice(1).toLowerCase();
        subtab = subtab.replace(/ /g,"%20");
        var module_url = {data : eval("kmc.modules." + module + ".swf_url")};
        //	alert("module_url="+module_url.data);
        var attributes = kmc.utils.mergeJson(kmc.modules.shared.attributes,module_url);
        var flashvars = kmc.utils.mergeJson(kmc.modules.shared.flashvars,eval("kmc.modules." + module + ".flashvars"),{ subNavTab : subtab });
        flashvars = { flashvars : kmc.utils.jsonToQuerystring(flashvars) };
        var params = kmc.utils.mergeJson(kmc.modules.shared.params,flashvars);
        //			params.wmode = (module == "reports") ? "window" : "opaque";
        //			if(module == "settings") {
        //					params.wmode = "opaque";
        //			}
        //			alert(params.wmode);
        //	alert("swfobject.createSWF("+attributes+", "+params+", "+kcms+")");
        window.kmc_module = swfobject.createSWF(attributes, params, "kcms");
        if(kmc.vars.kcw_open) {
            kmc.utils.hideFlash(true);
            kmc.functions.openKcw();
            kmc.vars.kcw_open = false;
        }
        //			alert($("#kcms"));
    },
    writeUrlHash : function(module,subtab){
        //	alert("writeUrlHash");
        //			if(module == "account")
        //				module = "Settings";
        location.hash = module + "|" + subtab;
        document.title = "KMC > " + module + ((subtab && subtab != "") ? " > " + subtab + " |" : "");
        //			document.title = "KMC > " + module.charAt(0).toUpperCase() + module.slice(1) + ((subtab && subtab != "") ? " > " + subtab + " |" : "");
    },
    readUrlHash : function() {
        var module = "dashboard", // @todo: change to kmc.vars.default_state.module ?
        subtab = "";
        try {
            var hash = location.hash.split("#")[1].split("|");
        }
        catch(err) {
            var nohash=true;
            //				err = null;
        }
        if(!nohash && hash[0]!="") {
            module = hash[0];
            subtab = hash[1];
            extra = {};
            if (hash[2])
            {
                var tmp = hash[2].split("&");
                for (var i = 0; i<tmp.length; i++)
                {
                    var tmp2 = tmp[i].split(":");
                    extra[tmp2[0]] = tmp2[1];
                }
            }
        }
        return { "moduleName" : module, "subtab" : subtab, "extra" : extra };
    },
    selectContent : function(uiconf_id,is_playlist) { // called by selectPlaylistContent which is caled from appstudio
        //			alert("selectContent("+uiconf_id+","+is_playlist+")");
        var subtab = is_playlist ? "playlists" : "manage";
        //			kmc.vars.current_uiconf = uiconf_id; // used by doPreviewEmbed
        kmc.vars.current_uiconf = { "uiconf_id" : uiconf_id , "is_playlist" : is_playlist }; // used by doPreviewEmbed
        kmc.mediator.setState( { module : "content", subtab : subtab } );
    }
};

kmc.preview_embed = {

    // called from p&e dropdown, from content.swf and from appstudio.swf
    doPreviewEmbed : function(id, name, description, previewOnly, is_playlist, uiconf_id, live_bitrates, has_mobile_flavors, html5_compatible) {
        kmc.log('doPreviewEmbed');
        kmc.log(arguments);
		
        // default value for html5_compatible
        html5_compatible = (html5_compatible) ? html5_compatible : false;
	html5_compatible = (previewOnly) ? false : html5_compatible;
		
        if(id != "multitab_playlist") {

            name = kmc.utils.escapeQuotes(name);
            description = kmc.utils.escapeQuotes(description); // @todo: move to "// JW" block

            if(kmc.vars.current_uiconf) { // set by kmc.mediator.selectContent called from appstudio's "select content" action
                if((is_playlist && kmc.vars.current_uiconf.is_playlist) || (!is_playlist && !kmc.vars.current_uiconf.is_playlist)) { // @todo: minor optimization possible
                    var uiconf_id = kmc.vars.current_uiconf.uiconf_id;
                    //alert("doPreviewEmbed says:\nkmc.vars.current_uiconf true -> uiconf_id = "+uiconf_id);
                }
                kmc.vars.current_uiconf = null;
            }

            if(!uiconf_id) { // get default uiconf_id (first one in list)
                var uiconf_id = is_playlist ? kmc.vars.playlists_list[0].id : kmc.vars.players_list[0].id;
                //alert(uiconf_id);
            }

            if(uiconf_id > 899 && uiconf_id < 1000) {
                kmc.vars.silverlight = true;
            }
            // JW
            else if(uiconf_id > 799 && uiconf_id < 900) {
                kmc.vars.jw = true,
                jw_license_html = '<strong>COMMERCIAL</strong>',
                jw_options_html = '',
                jw_nomix_box_html = kmc.preview_embed.jw.showNoMix(false,"check");

                if(kmc.vars.jw_swf == "non-commercial.swf") {
                    jw_license_html =   '<a href="http://creativecommons.org/licenses/by-nc-sa/3.0/" target="_blank" class="license tooltip"' +
                        'title="With this license your player will show a JW Player watermark.  You may NOT use the non-commercial' +
                        'JW Player on commercial sites such as: sites owned or operated by corporations, sites with advertisements,' +
                        'sites designed to promote a product, service or brand, etc.  If you are not sure whether you need to '+
                        'purchase a license, contact us.  You also may not use the AdSolution monetization plugin ' +
                        '(which lets you make money off your player).">NON-COMMERCIAL <img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" />' +
                        '</a>&nbsp;&bull;&nbsp;<a href="http://corp.kaltura.com/about/contact?subject=JW%20Player%20to%20commercial%20license&amp;' +
                        '&amp;pid=' + kmc.vars.partner_id + '&amp;name=' + kmc.vars.screen_name + '&amp;email=' + kmc.vars.email  + '" target="_blank" class="license tooltip" ' +
                        'title="Go to the Contact Us page and call us or fill in our Contact form and we\'ll call you (opens in new window/ tab).">Upgrade ' +
                        '<img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" /></a>';
                    var jw_license_ads_html = '<li>Requires <a href="http://corp.kaltura.com/about/contact?subject=JW%20Player%20to%20commercial%20license&amp;" ' +
                        'class="tooltip" title="With a Commercial license your player will not show the JW Player watermark and you will be ' +
                        'allowed to use the player on any site you want as well as use AdSolution (which lets you make money off your player)."' +
                        'target="_blank">Commercial license <img src="http://corp.kaltura.com/images/graphics/info.png" alt="show tooltip" /></a></li>';
                }
                jw_options_html =	'<div class="label">License Type:</div>\n<div class="description">' + jw_license_html + '</div>\n' +
                    '<div class="label">AdSolution:</div><div class="description"> <input type="checkbox" id="AdSolution" ' +
                    'onclick="kmc.preview_embed.jw.adSolution()" onmousedown="kmc.vars.jw_chkbox_flag=true" /> Enable ads ' +
                    'in your videos.&nbsp; <a href="http://www.longtailvideo.com/referral.aspx?page=kaltura&ref=azbkefsfkqchorl" ' +
                    'target="_blank" class="tooltip" title="Go to the JW website to sign up for FREE or to learn more about ' +
                    'running in-stream ads in your player from Google AdSense for Video, ScanScout, YuMe and others. (opens ' +
                    'in new window/ tab)"> Free sign up... <img src="http://corp.kaltura.com/images/graphics/info.png" alt="' +
                    'show tooltip" /></a><br />\n <ul id="ads_notes">\n  <li>Channel Code: <input onblur="' +
                    'kmc.preview_embed.jw.adsChannel(this, \'' + id + '\', \'' + name + '\', \'' + description + '\', ' + (is_playlist || false) + ', \'' + uiconf_id + '\');" ' +
                    'type="text" id="adSolution_channel" value="" /> <button>Apply</button></li>\n' + (jw_license_ads_html || '') +
                    '\n </ul>\n </div>\n';
            } // END JW
        } // end !multitab_playlist

        var embed_code, preview_player,
        id_type = is_playlist ? "Playlist " + (id == "multitab_playlist" ? "Name" : "ID") : "Embedding",
        uiconf_details = kmc.preview_embed.getUiconfDetails(uiconf_id,is_playlist);
			
        name = (name) ? name : '';
        //			kmc.log("uiconf_details="+uiconf_details);
        if(kmc.vars.jw) {
            embed_code = kmc.preview_embed.jw.buildJWEmbed(id, name, description, is_playlist, uiconf_id);
            preview_player = embed_code.replace('flvclipper', 'flvclipper/ks/' + kmc.vars.ks);
        }
        else if(kmc.vars.silverlight) {
            embed_code = kmc.preview_embed.buildSilverlightEmbed(id, name, is_playlist, uiconf_id);
            preview_player = embed_code.replace('{KS}','ks=' + kmc.vars.ks);
            embed_code = embed_code.replace('{KS}','');
            embed_code = embed_code.replace("{ALT}", ((kmc.vars.whitelabel) ? "" : "<br/>" + kmc.preview_embed.embed_code_template.kaltura_links));
        }
        else {
            embed_code = kmc.preview_embed.buildKalturaEmbed(id, name, description, is_playlist, uiconf_id);
            preview_player = embed_code.replace('{FLAVOR}','ks=' + kmc.vars.ks + '&');
            embed_code = embed_code.replace('{FLAVOR}','');
        }
        var modal_html = '<div id="modal"><div id="titlebar"><a id="close" href="#close"></a>' +
            '<a id="help" target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#contentSection118"></a>' + id_type +
            ': ' + name + '</div> <div id="modal_content">' +
            //							 ((typeof(live_bitrates) == "object") ? kmc.preview_embed.buildLiveBitrates(name,live_bitrates) : '') + // always return true because null is an object
        ((live_bitrates) ? kmc.preview_embed.buildLiveBitrates(name,live_bitrates) : '') +
            '<div id="player_wrap">' + preview_player + '</div>' +
            //							 ((id == "multitab_playlist") ? '' : kmc.preview_embed.buildSelect(id, name, description, is_playlist, uiconf_id)) +
        ((id == "multitab_playlist") ? '' : kmc.preview_embed.buildSelect(is_playlist, uiconf_id)) +
            (kmc.vars.jw ? jw_nomix_box_html : '') +
            (kmc.vars.jw ? jw_options_html : '') +
            ((kmc.vars.silverlight || live_bitrates) ? '' : kmc.preview_embed.buildRtmpOptions()) +
            ((html5_compatible) ? kmc.preview_embed.buildHTML5Option(id, kmc.vars.partner_id, uiconf_id, has_mobile_flavors) : '') +
            '<div class="embed_code_div"><div class="label">Embed Code:</div> <div class="right"><textarea id="embed_code" rows="5" cols=""' +
            // style="width:' + (parseInt(uiconf_details.width)-10) + 'px;"
        'readonly="true">' + embed_code + '</textarea></div><br class="clear" />' +
            '<div id="copy_msg">Press Ctrl+C to copy embed code (Command+C on Mac)</div><div class="center"><button id="select_code">' +
            '<span>Select Code</span></button></div></div></div></div>';
        //			alert(modal_html);
        kmc.vars.jw = false;
        kmc.vars.silverlight = false;

        kalturaCloseModalBox();

        kmc.utils.hideFlash(true);
			
        modal = kalturaInitModalBox ( null , { width : parseInt(uiconf_details.width) + 140 , height: parseInt(uiconf_details.height) + 200 } );
        modal.innerHTML = modal_html;
        $("#mbContent").addClass("new");
        // attach events here instead of writing them inline
        $("#embed_code, #select_code").click(function(){
            kmc.utils.copyCode();
        });
        $("#close").click(function(){
            kmc.utils.closeModal();
            return false;
        });
        $("#delivery_type").change(function(){
            kmc.vars.embed_code_delivery_type = this.value;
            kmc.preview_embed.doPreviewEmbed(id, name, description, previewOnly, is_playlist, uiconf_id, live_bitrates, has_mobile_flavors, html5_compatible);
        });
        $("#player_select").change(function(){
            kmc.preview_embed.doPreviewEmbed(id, name, description, previewOnly, is_playlist, this.value, live_bitrates, has_mobile_flavors, html5_compatible);
        });
			
        $("#html5_support").change(function(){
            var html5_support = ($(this).attr("checked")) ? true : false;
            var val = kmc.preview_embed.buildKalturaEmbed(id,name,description, is_playlist, uiconf_id, html5_support);
            $("#embed_code").val(val);
        });
			
        // show the embed code & enable the checkbox if its not a preview
        if (previewOnly==false) {
            $('.embed_code_div').show();
        }
        if(has_mobile_flavors) {
            $('#html5_support').attr('disabled', null);
        }
    }, // doPreviewEmbed

    buildLiveBitrates : function(name,live_bitrates) {
        //kmc.log('buildLiveBitrates');
        //kmc.log(arguments);
        var bitrates = "",
        len = live_bitrates.length,
        i;
        for(i=0;i<len;i++) {
            bitrates += live_bitrates[i].bitrate + " kbps, " + live_bitrates[i].width + " x " + live_bitrates[i].height + "<br />";
        }
        var lbr_data = 	'<dl style="margin: 0 0 15px">' + '<dt>Name:</dt><dd>' + name + '</dd>' +
            '<dt>Bitrates:</dt><dd>' + bitrates + '</dd></dl>';
        return lbr_data;
    },

    buildSilverlightEmbed : function(id, name, is_playlist, uiconf_id) {
        var uiconf_details = kmc.preview_embed.getUiconfDetails(uiconf_id,is_playlist),
        cache_st = kmc.preview_embed.setCacheStartTime(),
        embed_code = kmc.preview_embed.embed_code_template.silverlight;
        embed_code = embed_code.replace("{WIDTH}",uiconf_details.width);
        embed_code = embed_code.replace("{HEIGHT}",uiconf_details.height);
        embed_code = embed_code.replace("{HOST}",kmc.vars.host);
        embed_code = embed_code.replace("{CACHE_ST}",cache_st);
        embed_code = embed_code.replace("{VER}",uiconf_details.swfUrlVersion); // sl
        embed_code = embed_code.replace("{PARTNER_ID}",kmc.vars.partner_id);
        //			embed_code = embed_code.replace("{CDN_HOST}",kmc.vars.cdn_host); // sl
        embed_code = embed_code.replace("{UICONF_ID}",uiconf_id);
        embed_code = embed_code.replace(/{SILVERLIGHT}/gi,uiconf_details.minRuntimeVersion);
        embed_code = embed_code.replace("{INIT_PARAMS}",(is_playlist ? "playlist_id" : "entry_id"));
        embed_code = embed_code.replace("{ENTRY_ID}", id);
        return embed_code;
    },
    buildRtmpOptions : function() {
        var selected = ' selected="selected"';
        var delivery_type = kmc.vars.embed_code_delivery_type || "http";
        var html = '<div id="rtmp" class="label">Select Flash Delivery Type:</div> <div class="right"><select id="delivery_type">';
        var options = '<option value="http"' + ((delivery_type == "http") ? selected : "") + '>Progressive Download (HTTP)&nbsp;</option>' +
            '<option value="rtmp"' + ((delivery_type == "rtmp") ? selected : "") + '>Adaptive Streaming (RTMP)&nbsp;</option>';
        if(!kmc.vars.hide_akamai_hd_network) {
            options += '<option value="akamai"' + ((delivery_type == "akamai") ? selected : "") + '>Akamai HD Network &nbsp;</option>';
        }
        html += options + '</select></div><br /><div class="note">Adaptive Streaming automatically adjusts to the viewer\'s bandwidth,' +
            'while Progressive Download allows buffering of the content. <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#deliveryType">Read more</a></div><br />';
        return html;
    },
		
    buildHTML5Option : function(entry_id, partner_id, uiconf_id, has_mobile_flavors) {
        kmc.log('buildHTML5Option');
        kmc.log(arguments);
			
        var long_url = kmc.vars.service_url + '/index.php/kmc/preview/partner_id/' + partner_id + '/entry_id/' + entry_id + '/uiconf_id/' + uiconf_id + '/delivery/' + kmc.vars.embed_code_delivery_type;
        kmc.client.getShortURL(long_url);
			
        var description = '<div class="note red">This video does not have video flavors compatible with IPhone & IPad. <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#html5Support">Read more</a></div>';
        if(has_mobile_flavors) {
            description = '<div class="note">If you enable the HTML5 player, the viewer device will be automatically detected.' +
                ' <a target="_blank" href="' + kmc.vars.service_url + '/index.php/kmc/help#html5Support">Read more</a>' +
                '<br class"clear" />View player outside KMC: <span class="preview_url"><img src="/lib/images/kmc/url_loader.gif" alt="loading..." /> Updating Short URL...</span></div>';
        }
        var html = '<div class="label checkbox"><input id="html5_support" type="checkbox" disabled="disabled" /> <label for="html5_support">Support iPhone' +
            ' &amp; iPad with HTML5</label></div><br />' + description + '<br />';
        return html;
    },

    // for content|Manage->drilldown->flavors->preview
    // flavor_details = json:
    doFlavorPreview : function(entry_id, entry_name, flavor_details) {
        //			kmc.log(flavor_details);
        //			alert("doFlavorPreview(entry_id="+entry_id+", entry_name="+entry_name+", flavor_details logged)");
        entry_name = kmc.utils.escapeQuotes(entry_name);
        //			var flavor_asset_name = kmc.utils.escapeQuotes(flavor_details.flavor_name) || "unknown";
        kalturaCloseModalBox();
        kmc.utils.hideFlash(true);
        modal = kalturaInitModalBox ( null , { width : parseInt(kmc.vars.default_kdp.width) + 20 , height: parseInt(kmc.vars.default_kdp.height) + 10 } );
        $("#mbContent").addClass("new");
        var player_code = kmc.preview_embed.buildKalturaEmbed(entry_id,entry_name,null,false,kmc.vars.default_kdp);
{'fraction_non_alphanumeric': 0.16008310470660309, 'fraction_numerical': 0.0059664917561196495, 'mean_word_length': 2.226079484425349, 'pattern_counts': {'":': 10, '<': 351, '<?xml version=': 0, '>': 355, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5075461', 'n_tokens_mistral': 24458, 'n_tokens_neox': 23295, 'n_words': 4571}