package ads

import (
	"alpha/adDelivery/helper"
	"alpha/adDelivery/structure"
	config "alpha/configuration"
	"alpha/db"
	"crypto/md5"
	"encoding/hex"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/elliotchance/phpserialize"
)

func AdRenderOutstreamVideoAd(adDetails *AdDetails, zn structure.ZoneDetails, r *http.Request) {

	table_prefix := config.GetConfig("prefix", "table")
	var client_table = table_prefix + "clients"
	var campaign_table = table_prefix + "campaigns"
	var adservingid string
	adservingid = helper.RandToken(5) + strconv.Itoa(adDetails.Ad_id)
	hasher := md5.New()
	hasher.Write([]byte(adservingid))
	adservingid = hex.EncodeToString(hasher.Sum(nil))

	/*Advertiser*/
	type Advertiser struct {
		Clientid       int
		Clientname, id string
		Clientexp      time.Time
	}

	var id string
	adv := Advertiser{}

	Placement_id_str := strconv.Itoa(adDetails.Placement_id)
	redisClients.GetKey("client_"+Placement_id_str, &adv)

	if adv.Clientid == 0 {
		db.DbQueryRow("select cl.clientid as clientid,cl.clientname as name,c.expire_time as expire_time from "+client_table+" as cl,"+campaign_table+" as c where c.clientid=cl.clientid and c.campaignid=?", adDetails.Placement_id).Scan(&adv.Clientid, &adv.Clientname, &adv.Clientexp)

		redisClients.SetKey("client_"+Placement_id_str, &adv)
	} else {
	}

	rt := rand.Intn(999999)
	id = "vjs_" + strconv.Itoa(rt)
	rand1 := helper.RandToken(5)

	var bnrParams map[interface{}]interface{}
	phpserialize.Unmarshal([]byte(adDetails.Parameters), &bnrParams)

	var video_url, destination_url, iconUrl, cta_text, title, sponser_text, textDesc, vid_delpath, bg_image string

	if bnrParams["destination_url"] != "" {
		destination_url = bnrParams["destination_url"].(string)
	} else {
		destination_url = ""
	}

	if bnrParams["icon_url"] != "" {
		iconUrl = bnrParams["icon_url"].(string)
	} else {
		iconUrl = ""
	}

	if bnrParams["cta_text"] != "" {
		cta_text = bnrParams["cta_text"].(string)
	} else {
		cta_text = ""
	}

	if bnrParams["title"] != "" {
		title = bnrParams["title"].(string)
	} else {
		title = ""
	}

	if bnrParams["sponser_text"] != "" {
		sponser_text = bnrParams["sponser_text"].(string)
	} else {
		sponser_text = ""
	}

	if bnrParams["text_description"] != "" {
		textDesc = bnrParams["text_description"].(string)
	} else {
		textDesc = ""
	}

	/*if bnrParams["height"] != ""{
		height = bnrParams["height"].(string)
	}else{
		height = ""
	}

	if bnrParams["width"] != ""{
		width = bnrParams["width"].(string)
	}else{
		width = ""
	}*/

	if bnrParams["bg_image"] != "" {
		bg_image = bnrParams["bg_image"].(string)
	} else {
		bg_image = ""
	}

	if bnrParams["vid_upload_type"] == "External" {
		video_url = bnrParams["video_url"].(string)
	} else if bnrParams["vid_upload_type"] == "Internal" {
		video_url = config.GetConfig("protocol", "webpath") + config.GetConfig("images", "webpath") + "/" + bnrParams["rm_video"].(string)
	}

	video_url = "https://app.admaru.com/AdmaruAdDelivery/AdmaruVideoDelivery/videoplayback.mp4"

	zoneid := strconv.Itoa(zn.Zoneid)
	adid := strconv.Itoa(adDetails.Ad_id)
	campaign_id := strconv.Itoa(adDetails.Placement_id)

	vid_delpath = vastXml(adDetails, zn)

	if bnrParams["vid_type"] == "Internal" {

		vid_delpath = config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/xml_response/vast3xml.php?zoneid=` + zoneid + `&campaignid=` + campaign_id + `&bannerid=` + adid
	} else {

		vid_delpath = config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/xml_response/vast3_wrapperxml.php?zoneid=` + zoneid + `&campaignid=` + campaign_id + `&bannerid=` + adid
	}

	var externalAdStyle, s, s1 string
	s = config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.js`
	s1 = config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/jquery.min.js`

	encs := md5.New()
	encs.Write([]byte(s))
	encs1 := md5.New()
	encs1.Write([]byte(s1))

	if bnrParams["ad_type"] == "1" || bnrParams["vid_type"] == "External" { //In Article

		adDetails.Html = `<link rel="stylesheet" href="` + config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.css" type="text/css">

			<script>
		
				if (typeof fluidplayer_scripts == 'undefined') 
				{
						var fluidplayer_scripts = [];
				}
	
				function loadScript(url,md5, callback)
				{
					if(fluidplayer_scripts.includes(md5) == false)
					{
					
					
				    var script = document.createElement("script");
				    script.type = "text/javascript"; 

				    if (script.readyState){ 
				        script.onreadystatechange = function(){
				            if (script.readyState == "loaded" ||
				                    script.readyState == "complete"){
				                script.onreadystatechange = null;
				                callback();

				            }
				        };
				    } else {  
				        script.onload = function(){
							callback();	
				        };
				    }

				    script.src = url;
				    document.getElementsByTagName("head")[0].appendChild(script);
				    
				    fluidplayer_scripts.push(md5);
					
					}
					else
					{
					setTimeout(function() {
						callback();
						}, 1000); 
					}
				}
				
				loadScript("` + s + `","` + hex.EncodeToString(encs.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
				loadScript("` + s1 + `","` + hex.EncodeToString(encs1.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
			</script>

			<style>            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }
	            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }

	            @media only screen and (min-width: 10px) and (max-width: 299px)
	            {
	                #` + id + `
	                {
	                    height: 150px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 300px) and (max-width: 399px)
	            {
	                #` + id + `
	                {
	                    height: 200px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 400px) and (max-width: 650px)
	            {
	                #` + id + `
	                {
	                    height: 300px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 651px) and (max-width: 800px)
	            {
	                #` + id + `
	                {
	                    height: 400px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 801px) and (max-width: 1000px)
	            {
	                #` + id + `
	                {
	                    height: 500px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 1001px) and (max-width: 2000px)
	            {
	                #` + id + `
	                {
	                    height: 600px; 
	                    width: auto;  
	                }
	            }
	            @media only screen and (min-width: 2001px)
	                #` + id + `
	                {
	                    height: 700px; 
	                    width: auto; 
	                }
	            }
	            
            </style>
             
            <div id="test-ad` + rand1 + `">
	   			<style>
					.fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
					{
					    display: none !important;

					}
		        	#admedia` + rand1 + ` img
		        	{
		            	position: relative !important;
		        	}
		        	
		        	
		        </style>

		        <div id="admedia` + rand1 + `">
					<div class="rm_videowrapper` + id + `" id="rm_videowrapper` + id + `">
				        <center><span style="font-size:1.5vh;">ADVERTISEMENT</span></center>
						<center><video id="` + id + `"  autoplay="false" muted="muted">
		                    <source src="` + video_url + `" type="video/mp4">
		                </video></center>
				        <span></span>
				        
			        </div>
		        </div>
	        </div>	
      		<script> 
        
	    		function tracking_event_` + id + `(track_type) {
	                if(fluidPlayer` + id + `_run == 1) {
	        		var track_url = "` + config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/fc.php?script=rmvideoAds:rmvastEvent&bannerid=` + strconv.Itoa(adDetails.Ad_id) + `&zoneid=` + strconv.Itoa(zn.Zoneid) + `&event="+track_type;

	                    $.ajax({
	                        type: "get",
	                        url: track_url,
	                        cache: false,
	                        success: function (json) {
	                            try {
	                                console.log("Track event success");
	                            } catch (e) {
	                                console.log("Exception while request..");
	                            }
	                        },
	                        error: function () {
	                            console.log("Error while request..");
	                        }
	                    });
	                }
	            }


	            var fluidPlayer` + id + `_run = 1;  
		           
	            var icc` + id + ` = 0;
			    function load_ply_` + id + `() {   
					icc` + id + `++;

					if(icc` + id + ` != 2 ) {

					return false;
				}

	            var fluidPlayer` + id + ` = fluidPlayer("` + id + `", {
	                layoutControls: {
	                    primaryColor: false,
	                    playButtonShowing: true,
	                    playPauseAnimation: true,
	                    fillToContainer: false,
	                    autoPlay: false,
	                    preload: false,
	                    mute: true,
	                    doubleclickFullscreen: false,
	                    subtitlesEnabled: false,
	                    keyboardControl: true,
	                    layout: "default",
	                    allowDownload: false,
	                    playbackRateEnabled: false,
	                    allowTheatre: false,
	                    title: false,
	                    controlBar: {
	                        autoHide: false
	                    }
	                },
	                "vastOptions": {
	                    "allowVPAID": "true", 
	                    "adList": [
	                        {
	                            "roll": "preRoll",
	                            "vastTag": "` + vid_delpath + `",
	                            "adClickable": "true"
	                        }
	                    ],
	                    vastAdvanced: {
	                        vastLoadedCallback:       (function() {}),
	                        noVastVideoCallback:      (function() {}),
	                        vastVideoSkippedCallback: (function() { 
	                            $("#rm_videowrapper` + id + `").slideUp(800);
	                            show_vid = 4; 
	                            tracking_event_` + id + `("skip"); 
	                            fluidPlayer` + id + `_run = 0;
	                        }),
	                        vastVideoEndedCallback:   (function() { 
	                            $("#rm_videowrapper` + id + `").slideUp(800);
	                            show_vid = 4; 
	                            tracking_event_` + id + `("complete"); 
	                            fluidPlayer` + id + `_run = 0;
	                        })
	                    }
	                }
	            });

        	    fluidPlayer` + id + `.on("pause", function(){ tracking_event_` + id + `("pause"); });
	            fluidPlayer` + id + `.on("theatreModeOn", function(){ tracking_event_` + id + `("fullscreen"); });
	            fluidPlayer` + id + `.on("theatreModeOff", function(){ tracking_event_` + id + `("exitfullscreen"); });
           
                setTimeout(function(){ 
                    fluidPlayer` + id + `.pause(); 
                },2000);
                
                var height` + id + ` = $("#rm_videowrapper` + id + `").height();
                var width` + id + ` = $("#rm_videowrapper` + id + `").width();

                var div_position` + id + ` = $("#rm_videowrapper` + id + `").offset();
            	var visible_height` + id + ` = height` + id + `/2;
                
                $("#rm_videowrapper` + id + `").hide();
                var show_vid` + id + ` = 1;

                var visible_height` + id + ` = height` + id + `/2;
                var user_pause` + id + ` = 0;

                $("#` + id + `_fluid_control_playpause").click(function() {
                    (user_pause` + id + ` == 0) ? user_pause` + id + ` = 1 : user_pause` + id + ` = 0;
                });
                var first_occuresce` + id + ` = 0;

                $(window).scroll(function()
                {
                    var visible_height_up` + id + ` = div_position` + id + `.top+(visible_height` + id + `);
                    var screen_height` + id + ` = $(window).height();
                    var visible_height_down` + id + ` = (div_position` + id + `.top+visible_height` + id + `)-screen_height` + id + `;
                    scroll_position` + id + ` = $(window).scrollTop();

                    if(scroll_position` + id + ` >= visible_height_up` + id + ` || scroll_position` + id + ` <= visible_height_down` + id + `)
                    {
                        fluidPlayer` + id + `.pause();
                    }
                    else
                    {
                        if(user_pause` + id + ` == 0)
                        {
                            fluidPlayer` + id + `.play(); 	
                        }
                        
                        if(first_occuresce` + id + ` == 0)
                        {
                            $("#rm_videowrapper` + id + `").slideDown(800);
                            first_occuresce` + id + ` = 1;
                        }
                    }
                });

            	$(window).scroll();
         	}
                
    		</script> 
		</div>`

	} else if bnrParams["ad_type"] == "2" || bnrParams["vid_type"] == "External" {

		externalAdStyle = `<style>            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }
	            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }

	            @media only screen and (min-width: 10px) and (max-width: 299px)
	            {
	                #` + id + `
	                {
	                    height: 150px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 300px) and (max-width: 399px)
	            {
	                #` + id + `
	                {
	                    height: 200px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 400px) and (max-width: 650px)
	            {
	                #` + id + `
	                {
	                    height: 300px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 651px) and (max-width: 800px)
	            {
	                #` + id + `
	                {
	                    height: 400px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 801px) and (max-width: 1000px)
	            {
	                #` + id + `
	                {
	                    height: 500px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 1001px) and (max-width: 2000px)
	            {
	                #` + id + `
	                {
	                    height: 600px; 
	                    width: auto;  
	                }
	            }
	            @media only screen and (min-width: 2001px)
	                #` + id + `
	                {
	                    height: 700px; 
	                    width: auto; 
	                }
	            }

	       		</style>`

		adDetails.Html = `<link rel="stylesheet" href="` + config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.css" type="text/css">

			<script>
		
				if (typeof fluidplayer_scripts == 'undefined') 
				{
						var fluidplayer_scripts = [];
				}
	
	
				function loadScript(url,md5, callback)
				{
					if(fluidplayer_scripts.includes(md5) == false)
					{
					
					
				    var script = document.createElement("script");
				    script.type = "text/javascript";

				    if (script.readyState){ 
				        script.onreadystatechange = function(){
				            if (script.readyState == "loaded" ||
				                    script.readyState == "complete"){
				                script.onreadystatechange = null;
				                callback();

				            }
				        };
				    } else {  
				        script.onload = function(){
							callback();	
				        };
				    }

				    script.src = url;
				    document.getElementsByTagName("head")[0].appendChild(script);
				    
				    fluidplayer_scripts.push(md5);
					
					}
					else
					{
					setTimeout(function() {
						callback();
						}, 1000); 
					}
				    
					
					
				}

				loadScript("` + s + `","` + hex.EncodeToString(encs.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
				loadScript("` + s1 + `","` + hex.EncodeToString(encs1.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
				</script>
				
				
				<style>   
				 .fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
			{
			    display: none !important;

			}
			         
		            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
		            {
		                display: none;
		            }
		            
		            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
		            {
		                display: none;
		            }

		            @media only screen and (min-width: 10px) and (max-width: 299px)
		            {
		                #` + id + `
		                {
		                    height: 150px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 300px) and (max-width: 399px)
		            {
		                #` + id + `
		                {
		                    height: 200px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 400px) and (max-width: 650px)
		            {
		                #` + id + `
		                {
		                    height: 300px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 651px) and (max-width: 800px)
		            {
		                #` + id + `
		                {
		                    height: 400px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 801px) and (max-width: 1000px)
		            {
		                #` + id + `
		                {
		                    height: 500px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 1001px) and (max-width: 2000px)
		            {
		                #` + id + `
		                {
		                    height: 600px; 
		                    width: auto;  
		                }
		            }
		            @media only screen and (min-width: 2001px)
		                #` + id + `
		                {
		                    height: 700px; 
		                    width: auto; 
		                }
		            }
					.fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
					{
					    display: none !important;

					}
					
		        	#admedia` + rand1 + ` img
		        	{
		            	position: relative !important;
		        	}
		        	
		        	` + externalAdStyle + `
		        </style>
		        <div id="admedia` + rand1 + `">
					<div class="rm_videowrapper` + id + `" id="rm_videowrapper` + id + `">
				        <div>
				            <div>
				                <div style="width: 5.667% !important;">

				                <img src="` + iconUrl + `" style="border-radius:50%;width:50px;height:50px;">
				                   
				                </div>
				                <div>
				                    <div>
				                        <h5 style="margin-left:2px;font-weight: normal;">` + title + `</h5>
				                    </div>
				                    <div>
				                        <h6 style="margin-left:10px; font-weight: bold;">` + sponser_text + `</h6>
				                    </div>
				                </div>
				            </div>
				        </div>
				        <div>
				            <div>
				                <div>
				                    <p style="font-size:15px!important; line-height:1.5 !important;">` + textDesc + `</p>
				                </div>
				            </div>
				        </div>
				        <div>
				            <div>
				                <video id="` + id + `"  autoplay="false" muted="muted">
				                    <source src="` + video_url + `" type="video/mp4">
				                </video>
				            </div>
				        </div>
				        <div>
				            <div style="text-align:center;margin-top:1%;">
				               <a type="button" href="` + destination_url + `" target="_blank" class="btn btn-info">` + cta_text + `</a>
				            </div>
				        </div>
			        </div>
		        </div>

          		<script> 
        
		    		function tracking_event_` + id + `(track_type) {
		                if(fluidPlayer` + id + `_run == 1) {
		        		var track_url = "` + config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/fc.php?script=rmvideoAds:rmvastEvent&bannerid=` + strconv.Itoa(adDetails.Ad_id) + `&zoneid=` + strconv.Itoa(zn.Zoneid) + `&event="+track_type;

		                    $.ajax({
		                        type: "get",
		                        url: track_url,
		                        cache: false,
		                        success: function (json) {
		                            try { 
		                                console.log("Track event success");
		                            } catch (e) {
		                                console.log("Exception while request..");
		                            }
		                        },
		                        error: function () {
		                            console.log("Error while request..");
		                        }
		                    });
		                }
		            }

 
		            var fluidPlayer` + id + `_run = 1;  
		           
		            var icc` + id + ` = 0;
				    function load_ply_` + id + `() {   
						icc` + id + `++;

						if(icc` + id + ` != 2 ) {

						return false;
					}

		            var fluidPlayer` + id + ` = fluidPlayer(
		                "` + id + `", {
		                layoutControls: {
		                    primaryColor: false,
		                    playButtonShowing: true,
		                    playPauseAnimation: true,
		                    fillToContainer: false,
		                    autoPlay: false,
		                    preload: false,
		                    mute: true,
		                    doubleclickFullscreen: false,
		                    subtitlesEnabled: false,
		                    keyboardControl: true,
		                    layout: "default",
		                    allowDownload: false,
		                    playbackRateEnabled: false,
		                    allowTheatre: false,
		                    title: false,
		                    controlBar: {
		                        autoHide: false
		                    }
		                },
		                "vastOptions": {
		                    "allowVPAID": "true", 
		                    "adList": [
		                        {
		                            "roll": "preRoll",
		                            "vastTag": "` + vid_delpath + `",
		                            "adClickable": "true"
		                        }
		                    ],
		                    vastAdvanced: {
		                        vastLoadedCallback:       (function() {}),
		                        noVastVideoCallback:      (function() {}),
		                        vastVideoSkippedCallback: (function() { 
		                            $("#rm_videowrapper` + id + `").slideUp(800);
		                            show_vid = 4; 
		                            tracking_event_` + id + `("skip"); 
		                            fluidPlayer` + id + `_run = 0;
		                        }),
		                        vastVideoEndedCallback:   (function() { 
		                            $("#rm_videowrapper` + id + `").slideUp(800);
		                            show_vid = 4; 
		                            tracking_event_` + id + `("complete"); 
		                            fluidPlayer` + id + `_run = 0;
		                        })
		                    }
		                }
		            });

        
		            fluidPlayer` + id + `.on("play", function(){ tracking_event_` + id + `("resume"); });

		            fluidPlayer` + id + `.on("pause", function(){ tracking_event_` + id + `("pause"); });

		            fluidPlayer` + id + `.on("theatreModeOn", function(){ tracking_event_` + id + `("fullscreen"); });

		            fluidPlayer` + id + `.on("theatreModeOff", function(){ tracking_event_` + id + `("exitfullscreen"); });

           
	                setTimeout(function(){ 
	                    fluidPlayer` + id + `.pause(); 
	                },2000);
	                
	                var height` + id + ` = $("#rm_videowrapper` + id + `").height();
	                var width` + id + ` = $("#rm_videowrapper` + id + `").width();

	                var div_position` + id + ` = $("#rm_videowrapper` + id + `").offset();
	                $("#rm_videowrapper` + id + `").hide();
	                var show_vid` + id + ` = 1;

	                var visible_height` + id + ` = height` + id + `/1.5;

	                var user_pause` + id + ` = 0;

	                $("#` + id + `_fluid_control_playpause").click(function()
	                {
	                    (user_pause` + id + ` == 0) ? user_pause` + id + ` = 1 : user_pause` + id + ` = 0;
	                });

	                $(window).scroll(function()
	                {
	                    var visible_height_up` + id + ` = div_position` + id + `.top+(visible_height` + id + `);
	                    var screen_height` + id + ` = $(window).height();
	                    var visible_height_down` + id + ` = (div_position` + id + `.top+visible_height` + id + `)-screen_height` + id + `;


	                    scroll_position` + id + ` = $(window).scrollTop();

	                    if(scroll_position` + id + ` >= visible_height_up` + id + ` || scroll_position` + id + ` <= visible_height_down` + id + `)
	                    {
	                        if( show_vid` + id + ` != 1)
	                        {
	                            fluidPlayer` + id + `.pause();
	                        }
	                    }
	                    else
	                    {
	                        if( show_vid` + id + ` == 1 && user_pause` + id + ` == 0)
	                        {
	                            $("#rm_videowrapper` + id + `").css("opacity","1");
	                            setTimeout( function()  
	                            { 
	                                $("#rm_videowrapper` + id + `").slideDown(800);
	                                show_vid` + id + ` = 2 ;
	                                fluidPlayer` + id + `.play(); 
	                            },500);
	                        
	                        }
	                        else if(show_vid` + id + ` == 2 && user_pause` + id + ` == 0)
	                        {
	                            setTimeout( function()  { 
	                                fluidPlayer` + id + `.play(); 
	                                show_vid` + id + ` = 3; 
	                            },500);
	                            
	                        }
	                        else if(show_vid` + id + ` == 3 && user_pause` + id + ` == 0)
	                        {
	                            fluidPlayer` + id + `.play();
	                        }
	                    }
	                });

                	$(window).scroll();

	                $("#rm_videowrapper` + id + `").mouseenter(function()
	                {
	                    tracking_event_` + id + `("unmute");
	                    fluidPlayer` + id + `.setVolume(0.5);
	                });

	                $("#rm_videowrapper` + id + `").mouseout(function()
	                {
	                    tracking_event_` + id + `("mute");
	                    fluidPlayer` + id + `.setVolume(0.5); 
	                }); 
	         	}
                
    		</script> 
		</div>`

	} else if bnrParams["ad_type"] == "3" || bnrParams["vid_type"] == "External" {

		externalAdStyle = `<style>            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }
	            
	            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
	            {
	                display: none;
	            }

	            @media only screen and (min-width: 10px) and (max-width: 299px)
	            {
	                #` + id + `
	                {
	                    height: 150px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 300px) and (max-width: 399px)
	            {
	                #` + id + `
	                {
	                    height: 200px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 400px) and (max-width: 650px)
	            {
	                #` + id + `
	                {
	                    height: 300px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 651px) and (max-width: 800px)
	            {
	                #` + id + `
	                {
	                    height: 400px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 801px) and (max-width: 1000px)
	            {
	                #` + id + `
	                {
	                    height: 500px; 
	                    width: auto; 
	                }
	            }
	            @media only screen and (min-width: 1001px) and (max-width: 2000px)
	            {
	                #` + id + `
	                {
	                    height: 600px; 
	                    width: auto;  
	                }
	            }
	            @media only screen and (min-width: 2001px)
	                #` + id + `
	                {
	                    height: 700px; 
	                    width: auto; 
	                }
	            }

	       		</style>`

		adDetails.Html = `<link rel="stylesheet" href="` + config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.css" type="text/css">
				<script>
			


					if (typeof fluidplayer_scripts == 'undefined') 
					{
							var fluidplayer_scripts = [];
					}
		
		
					function loadScript(url,md5, callback)
					{
						if(fluidplayer_scripts.includes(md5) == false)
						{
						
						
					    var script = document.createElement("script");
					    script.type = "text/javascript";

					    if (script.readyState){ 
					        script.onreadystatechange = function(){
					            if (script.readyState == "loaded" ||
					                    script.readyState == "complete"){
					                script.onreadystatechange = null;
					                callback();

					            }
					        };
					    } else {  
					        script.onload = function(){
								callback();	
					        };
					    }

					    script.src = url;
					    document.getElementsByTagName("head")[0].appendChild(script);
					    
					    fluidplayer_scripts.push(md5);
						
						}
						else
						{
						setTimeout(function() {
							callback();
							}, 1000); 
						}
					    			
					}
					loadScript("` + s + `","` + hex.EncodeToString(encs.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
					loadScript("` + s1 + `","` + hex.EncodeToString(encs1.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
				</script>

				<style>            
		            .video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
					{
						display: none;
					}  

					@media only screen and (min-width: 100px) and (max-width: 790px)
					{
						#rm_videowrapper` + id + `{
							margin-top: 50%;
						}

					}	

					@media only screen and (min-width: 10px) and (max-width: 299px)
					{
						#` + id + `
						{
							position: relative;
							margin-top: 50%;
				   			height: 150px; 
				   			width: auto; 
						};
					}

		            @media only screen and (min-width: 300px) and (max-width: 399px)
		            {
		                #` + id + `
		                {
		                	position: relative;
							margin-top: 50%;
		                    height: 200px; 
		                    width: auto; 
		                }
		            }
		            
		            @media only screen and (min-width: 400px) and (max-width: 650px)
		            {
		                #` + id + `
		                {
		                	position: relative;
							margin-top: 50%;
		                    height: 300px; 
		                    width: auto; 
		                }
		            }
		            
		            @media only screen and (min-width: 651px) and (max-width: 900px)
		            {
		                #` + id + `
		                {
		                    height: 400px; 
		                    width: auto; 
		                }
		            }
		            @media only screen and (min-width: 901px)
		            {
		                #` + id + `
		                {
		                    height: 400px; 
				   			width: auto; 
				   			margin-top: 20px;
		                }
		            }
		            @media only screen and (min-width: 100px) and (max-width: 980px)
		            {
		               	.volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 26%;
							z-index: 1;
							
						}
		            }
		            @media only screen and(min-width: 981px) and (max-width: 1080px)
		            {
		                .volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 28%;
							z-index: 1;
							
						}
		            }

		            @media only screen and (min-width: 1081px) and (max-width: 1420px)
					{
						.volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 32%;
							z-index: 1;
						}
					}

					@media only screen and (min-width: 1421px) and (max-width: 1560px)
					{
						.volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 35%;
							z-index: 1;
						}
					}

					@media only screen and (min-width: 1561px) and (max-width: 1825px)
					{
						.volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 37%;
							z-index: 1;
						}
					}

					@media only screen and (min-width: 1826px) 
					{
						.volume_controls{
							position: relative;
							margin-top: -45px;
							float: left;
							left: 42%;
							z-index: 1;
						}
					}
		
					.fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
					{
					    display: none !important;

					}
    	
    				#rm_videowrapper` + id + `
					{
						margin-left: auto;
						margin-right: auto;
						width:  90%;
						height: 90%;
					}
					#intersitial_outstream` + id + `{
						position: fixed;
						z-index: 9999;
						background: rgba(0, 0, 0, 0.75);
						top: 0;
						    left: 0;

						width: 100%;
						height: 100%;
					}
					.text-white{
						color: #fff;
					}
					#interstitial-footer` + id + `{
						text-align : right;
						margin-left: 550px;
						padding-top: 10px;
					}
					
					
		        </style>

		        <div id="intersitial_outstream` + id + `">
					<div id="rm_videowrapper` + id + `">
						<center>
							<video id="` + id + `" autoplay="false" muted="muted" style="position: relative;"><source src="` + video_url + `" type="video/mp4"></video>
							<div class="interstitial-footer" id="interstitial-footer" >
						    	<button type="button" class="btn btn-primary" id="close_interstitial_ad` + id + `" data-dismiss="modal">Close</button>
						    </div>
						</center>
					</div>
				</div>

				<script> 
	    	var fluidPlayer` + id + `_run = 1;
	    	
	    	   function tracking_event_` + id + `(track_type) {
	        	if(fluidPlayer` + id + `_run == 1) {
        		var track_url = "` + config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/fc.php?script=rmvideoAds:rmvastEvent&bannerid=` + strconv.Itoa(adDetails.Ad_id) + `&zoneid=` + strconv.Itoa(zn.Zoneid) + `&event="+track_type;

	        		$.ajax({
					    type: "get",
					    url: track_url,
					    cache: false,
					    success: function (json) {
					        try {
					        	console.log("Track event success");
					        } catch (e) {
					            console.log("Exception while request..");
					        }
					    },
					    error: function () {
					        console.log("Error while request..");
					    }
					});
	        	}
	        }
	        
	        
    	  	var icc` + id + ` = 0;
     		function load_ply_` + id + `() {   
				icc` + id + `++;
				if(icc` + id + ` != 2 ) {
					return false;
				}	  	
		  	

	    	var fluidPlayer` + id + ` = fluidPlayer("` + id + `", {
	    		layoutControls: {
		            primaryColor:           false,
		            playButtonShowing:      true,
		            playPauseAnimation:     true,
		            fillToContainer:        false,
		            autoPlay:               false,
		            preload:                false,
		            mute:                   true,
		            doubleclickFullscreen:  true,
		            subtitlesEnabled:       false,
		            keyboardControl:        true,
		            layout:                 "default",
		            allowDownload:          false,
		            playbackRateEnabled:    false,
		            allowTheatre:           true,
		            title:                  false,
		            controlBar: {
		                autoHide:           false
		            }
		        },
	            "vastOptions": {
	            	maxAllowedVastTagRedirects: 1,
	                "allowVPAID": "true",
	                "adList": [
	                    {
	                        "roll": "preRoll",
	                        "vastTag": "` + vid_delpath + `",
	                        adClickable: true
	                    }
	                ],
	                vastAdvanced: {
	                	vastLoadedCallback:       (function() {}),
	                	noVastVideoCallback:      (function() {}),
		                vastVideoSkippedCallback: (function() { 
		                	$("#intersitial_outstream").slideUp(800);
		                	show_vid = 4;
		                	tracking_event_` + id + `("skip"); 
		                	fluidPlayer` + id + `_run = 0; 
		                }),
		                vastVideoEndedCallback:   (function() { 
		                	$("#intersitial_outstream").slideUp(800);
		                	show_vid = 4; 
		                	tracking_event_` + id + `("complete"); 
		                	fluidPlayer` + id + `_run = 0;
		                })
		            }
	            }
	        });

	     

	        fluidPlayer` + id + `.on("play", function(){ tracking_event_` + id + `("resume"); });
	        fluidPlayer` + id + `.on("pause", function(){ tracking_event_` + id + `("pause"); });
	        fluidPlayer` + id + `.on("theatreModeOn", function(){ tracking_event_` + id + `("fullscreen"); });
	        fluidPlayer` + id + `.on("theatreModeOff", function(){ tracking_event_` + id + `("exitfullscreen"); });

			
			
		
			fluidPlayer` + id + `.play();


			fluidPlayer` + id + `.on("ended", function()
			{	  
    			close_vid` + id + `();				
			});
	     

	        $("#close_interstitial_ad` + id + `").click(function(){
	        	close_vid` + id + `();
	        });

			}

	        function close_vid` + id + `()
	        {
	        	$("#intersitial_outstream` + id + `").slideUp(1000);
	        }     
	    </script>`

	} else if bnrParams["ad_type"] == "4" { //Infeed

		adDetails.Html = `<link rel="stylesheet" href="` + config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.css" type="text/css"/>
		<script>
		
			if (typeof fluidplayer_scripts == 'undefined')  {
					var fluidplayer_scripts = [];
			}

			function loadScript(url,md5, callback)
			{
				if(fluidplayer_scripts.includes(md5) == false)
				{
			    var script = document.createElement("script");
			    script.type = "text/javascript";

			    if (script.readyState){ 
			        script.onreadystatechange = function(){
			            if (script.readyState == "loaded" ||
			                    script.readyState == "complete"){
			                script.onreadystatechange = null;
			                callback();

			            }
			        };
			    } else {  
			        script.onload = function(){
						callback();	
			        };
			    }

			    script.src = url;
			    document.getElementsByTagName("head")[0].appendChild(script);
			    
			    fluidplayer_scripts.push(md5);
				
				}
				else
				{
				setTimeout(function() {
					callback();
					}, 1000); 
				}
			}
			loadScript("` + s + `","` + hex.EncodeToString(encs.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
			loadScript("` + s1 + `","` + hex.EncodeToString(encs1.Sum(nil)) + `", function() {  load_ply_` + id + `()   }  );
		</script>
		<style>
			.video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
			{
				display: none;
			}
			@media only screen and (min-width: 10px) and (max-width: 299px)
			{
				#` + id + `
				{
		   			height: 150px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 300px) and (max-width: 399px)
			{
				#` + id + `
				{
		   			height: 200px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 400px) and (max-width: 650px)
			{
				#` + id + `
				{
		   			height: 300px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 651px) and (max-width: 800px)
			{
				#` + id + `
				{
		   			height: 400px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 801px) and (max-width: 1000px)
			{
				#` + id + `
				{
		   			height: 500px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 1001px) and (max-width: 2000px)
			{
				#` + id + `
				{
		   			height: 600px; 
		   			width: auto; 
				}
			}
			@media only screen and (min-width: 2001px)
				#` + id + `
				{
		   			height: 700px; 
		   			width: auto; 
				}
			}
		</style>
		<div id="test-ad` + rand1 + `">
		   	<style>
          		.fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
				{
				    display: none !important;

				} 
            	.admedia` + rand1 + ` img
            	{
                	position: relative !important;
            	}           	
            	
            </style>
	        <div class="admedia` + rand1 + `" >
				<center>
					<div id="outstream` + id + `" style="background-color: white;" >
						<video id="` + id + `" autoplay="false" muted="muted" style="position: relative;">	 
							<source src="` + video_url + `" type="video/mp4">	
						</video>
					</div>
				</center>
			</div>
		</div>

    	<script> 
		   var fluidPlayer` + id + `_run = 1;
         
        
        	function tracking_event_` + id + `(track_type) {
    			if(fluidPlayer` + id + `_run == 1) {
    				var track_url = "` + config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/fc.php?script=rmvideoAds:rmvastEvent&bannerid=` + strconv.Itoa(adDetails.Ad_id) + `&zoneid=` + strconv.Itoa(zn.Zoneid) + `&event="+track_type;

        			$.ajax({
					    type: "get",
					    url: track_url,
					    cache: false,
					    success: function (json) {
					        try {
					        	console.log("Track event success");
					        } catch (e) {
					            console.log("Exception while request..");
					        }
					    },
					    error: function () {
					        console.log("Error while request..");
					    }
					});
	        	}
        	}

     		var fluidPlayer` + id + `_run = 1;   
            
    		var icc` + id + ` = 0;
 			function load_ply_` + id + `() {   
				icc` + id + `++;
				if(icc` + id + ` != 2 ) {
					return false;
				}  	
	    		var fluidPlayer` + id + ` = fluidPlayer("` + id + `", {
    				layoutControls: {
			            primaryColor:           false,
			            playButtonShowing:      true,
			            playPauseAnimation:     true,
			            fillToContainer:        false,
			            autoPlay:               false,
			            preload:                false,
			            mute:                   true,
			            doubleclickFullscreen:  true,
			            subtitlesEnabled:       false,
			            keyboardControl:        true,
			            layout:                 "default",
			            allowDownload:          false,
			            playbackRateEnabled:    false,
			            allowTheatre:           true,
			            title:                  false,
			            controlBar: {
			                autoHide:           false
			            }
			        },
		            "vastOptions": {
		            	maxAllowedVastTagRedirects: 1,
		                "allowVPAID": "true", 
		                "adList": [
		                    {
		                        "roll": "preRoll",
		                        "vastTag": "` + vid_delpath + `",
		                        adClickable: true
		                    }
		                ],
                		vastAdvanced: {
                			vastLoadedCallback: (function() {}),
                			noVastVideoCallback: (function() {}),
	                		vastVideoSkippedCallback: (function() { 
                				$("#outstream` + id + `").slideUp(800);
	                			show_vid = 4;
	                			tracking_event_` + id + `("skip"); 
	                			fluidPlayer` + id + `_run = 0; 
                			}),
	                		vastVideoEndedCallback: (function() { 
	                			$("#outstream` + id + `").slideUp(800);
	                			show_vid = 4;
	                			tracking_event_` + id + `("complete"); 
	                			fluidPlayer` + id + `_run = 0; 
                			})
	            		}
            		}
        		});

		        fluidPlayer` + id + `.on("play", function(){ tracking_event_` + id + `("resume"); });
		        fluidPlayer` + id + `.on("pause", function(){ tracking_event_` + id + `("pause"); });
		        fluidPlayer` + id + `.on("theatreModeOn", function(){ tracking_event_` + id + `("fullscreen"); });
		        fluidPlayer` + id + `.on("theatreModeOff", function(){ tracking_event_` + id + `("exitfullscreen"); });

				setTimeout(function(){ 
					fluidPlayer` + id + `.pause(); 
				},2000);

				var height` + id + ` = $("#outstream` + id + `").height();
				var width` + id + `  = $("#outstream` + id + `").width();

				var div_position` + id + ` = $("#outstream` + id + `").offset();
				var visible_height` + id + ` = height` + id + `/2;

				$("#outstream` + id + `").css("opacity","0");
				$("#outstream` + id + `").hide(-9000);
				
				var show_vid` + id + ` = 1;

				var user_pause` + id + ` = 0;

				$("#` + id + `_fluid_control_playpause").click(function()  {
					(user_pause` + id + ` == 0) ? user_paus` + id + ` = 1 : user_pause` + id + ` = 0;
				});
			
				$(window).scroll(function()
				{ 					
					var visible_height_up` + id + ` = div_position` + id + `.top+(visible_height` + id + `);
					var screen_height` + id + ` = $(window).height();
					var visible_height_down` + id + ` = (div_position` + id + `.top+visible_height` + id + `)-screen_height` + id + `;

					scroll_position` + id + ` = $(window).scrollTop();

					if(scroll_position` + id + ` >= visible_height_up` + id + ` || scroll_position` + id + ` <= visible_height_down` + id + `)
					{
						if( show_vid` + id + ` != 1)
						{
							fluidPlayer` + id + `.pause();
						}
					}
					else
					{

						if( show_vid` + id + ` == 1 && user_pause` + id + ` == 0)
						{
							$("#outstream` + id + `").css("opacity","1");
							$("#outstream` + id + `").slideDown(800);
							show_vid` + id + ` = 2 ;
							fluidPlayer` + id + `.play();
						}
						else if(show_vid` + id + ` == 2 && user_pause` + id + ` == 0)
						{
							fluidPlayer` + id + `.play();
						}
					}
				});

				$(window).scroll();

				$("#outstream` + id + `").mouseenter(function()
				{
					tracking_event_` + id + `("unmute");
				    fluidPlayer` + id + `.setVolume(0.5); 
				});

				$("#outstream` + id + `").mouseout(function()
				{
					tracking_event_` + id + `("mute");
				    fluidPlayer` + id + `.setVolume(0); 
				});
			}
		</script>`
	} else if bnrParams["ad_type"] == "5" { //In banner
		var bg_width, bg_height, inbwidth, inbheight, button_height, button_width, desc_top, font_size, button_left, rm_wrappertop string
		zone_size := helper.GetUrlParam(r, "zone_size")

		if zone_size == "1" && zone_size != "0" {
			bg_width = "300"
			bg_height = "250"
			inbwidth = "250"
			inbheight = "160"
			button_height = "25"
			button_width = "250"
			desc_top = "164"
			font_size = "12.5"
			button_left = "24"
			rm_wrappertop = "20"

		} else if zone_size == "2" {
			bg_width = "160"
			bg_height = "600"
			inbwidth = "110"
			inbheight = "300"
			button_width = "110"
			button_height = "25"
			font_size = "12.5"
			button_left = "24"
			rm_wrappertop = "22"
		} else if zone_size == "3" {
			bg_width = "728"
			bg_height = "90"
			inbwidth = "654"
			inbheight = "70"
			button_width = "100"
			button_height = "15"
			desc_top = "72"
			font_size = "7.5"
			button_left = "314"
			rm_wrappertop = "2"
		} else {
			bg_width = "300"
			bg_height = "250"
			inbwidth = "250"
			inbheight = "160"
			button_height = "25"
			button_width = "250"
			desc_top = "164"
			font_size = "12.5"
			button_left = "24"
			rm_wrappertop = "20"
		}

		adDetails.Html = `<link rel="stylesheet" href="` + config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fluid/fluidplayer.min.css" type="text/css"/>
		<script>
		
			if (typeof fluidplayer_scripts == 'undefined')  {
					var fluidplayer_scripts = [];
			}


			function loadScript(url,md5, callback)
			{
				if(fluidplayer_scripts.includes(md5) == false)
				{
			    var script = document.createElement("script");
			    script.type = "text/javascript";

			    if (script.readyState){ 
			        script.onreadystatechange = function(){
			            if (script.readyState == "loaded" ||
			                    script.readyState == "complete"){
			                script.onreadystatechange = null;
			                callback();

			            }
			        };
			    } else {  
			        script.onload = function(){
						callback();	
			        };
			    }

			    script.src = url;
			    document.getElementsByTagName("head")[0].appendChild(script);
			    
			    fluidplayer_scripts.push(md5);
				
				}
				else
				{
				setTimeout(function() {
					callback();
					}, 1000); 
				}
			}
			
			loadScript("` + s + `","` + hex.EncodeToString(encs.Sum(nil)) + `", function() {  load_ply_` + id + `();   }  );
			loadScript("` + s1 + `","` + hex.EncodeToString(encs1.Sum(nil)) + `", function() {  load_ply_` + id + `();   }  );
		</script>
		<style>
				.video-js .vjs-time-control, .video-js .vjs-fullscreen-control, .video-js .vjs-progress-control
				{
					display: none;
				}
			
				#` + id + `
				{
		   			width: ` + inbwidth + `px; 
		   			height: ` + inbheight + `px; 
				}

				#demo_vid` + id + `
				{
					width :` + bg_width + `px; 
					height:` + bg_height + `px;
					margin-bottom:5px!important;
				}
				#rm_description` + id + `
				{
					line-height: ` + button_height + `px; 
					font-size: ` + font_size + `px; 
					font-style: italic;
					color: black;
					position: absolute; 
					background: white; 
					width: ` + button_width + `px; 
					height: ` + button_height + `px; 
					top: ` + desc_top + `px;
					left: ` + button_left + `px;
				}

				#rm_videowrapper` + id + `
				{
					position: relative; 
					top: ` + rm_wrappertop + `%;
				}
				#rm_inbannerbg` + id + `
				{
					width: ` + bg_width + `px!important;
					height: ` + bg_height + `px!important;
				}
							
 
			</style>
			<div id="test-ad` + rand1 + `">
		   <style>
		   
			.fluid_context_menu, .fluid_controls_left , .fluid_control_duration , .ad_countdown  ,.fluid_controls_progress_container
			{
			    display: none !important;

			} 
            	.ad-media` + rand1 + ` img
            	{
                	position: relative !important;
            	}
            </style>
            
	        <div class="ad-media` + rand1 + `" >
			<div id="demo_vid` + id + `" style="margin-bottom:10px;">

				<center><span style="font-size:12px;">ADVERTISEMENT</span></center>
				<div style="position: absolute;">
					<img id="rm_inbannerbg` + id + `" src=` + bg_image + `>
				</div>
				<div id="rm_videowrapper` + id + `">

				<center>
					<video id="` + id + `" autoplay="false" muted="muted">
						<source src="` + video_url + `" type="video/mp4">
					</video>

					<a id="rm_clickurl` + id + `" target="'.$dest.'" href="` + destination_url + `">
						<span id="rm_description` + id + `">Click Here!</span>
					</a>

				</center>
				</div>
			</div>
			</div>
		</div>

   
 
		<script> 
			function tracking_event_` + id + `(track_type) {
	        	if(fluidPlayer` + id + `_run == 1) {
	        	
        		var track_url = "` + config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/fc.php?script=rmvideoAds:rmvastEvent&bannerid=` + strconv.Itoa(adDetails.Ad_id) + `&zoneid=` + strconv.Itoa(zn.Zoneid) + `&event="+track_type;

	        		$.ajax({
					    type: "get",
					    url: track_url,
					    cache: false,
					    success: function (json) {
					        try {
					        	console.log("Track event success");
					        } catch (e) {
					            console.log("Exception while request..");
					        }
					    },
					    error: function () {
					        console.log("Error while request..");
					    }
					});
	        	}
	        }
	        
	        fluidPlayer` + id + `_run = 0;
	        
	        var icc` + id + ` = 0;
		    function load_ply_` + id + `() {   
				icc` + id + `++;
				if(icc` + id + ` != 2 ) {
					return false;
				}

        		var fluidPlayer` + id + `_run = 1;

				var playerId` + id + ` = "` + id + `";

				var options` + id + ` = {
		    		layoutControls: {
		    			posterImage: "` + bg_image + `",
			            primaryColor: false,
			            playButtonShowing: false,
			            playPauseAnimation: false,
			            fillToContainer: false,
			            autoPlay: false,
			            preload: false,
			            mute: false,
			            doubleclickFullscreen: true,
			            subtitlesEnabled: false,
			            keyboardControl: false,
			            layout: "default",
			            allowDownload: false,
			            playbackRateEnabled: false,
			            allowTheatre: false,
			            title: false,
			            controlBar: {
			                autoHide: false
			            },
			          
						playerInitCallback: (function() {
				        	$("#` + id + `_fluid_control_volume_container").hide(); 
							$("#` + id + `_fluid_control_duration").hide(); 
							$("#` + id + `_fluid_control_fullscreen").hide();
			        	})
			        },
		            "vastOptions": {
		            	maxAllowedVastTagRedirects: 1,
		                "allowVPAID": "true", 
		                "adList": [
		                    {
		                        "roll": "preRoll",
		                        "vastTag": "` + vid_delpath + `",
		                        adClickable: true
		                    }
		                ],
		                vastAdvanced: {
		                	vastLoadedCallback: (function() {
		                		videoVAST = jQuery("#` + id + `").attr("src");
		                		$("#` + id + `").trigger("pause");	
	                		}),
	                		
		                	noVastVideoCallback:(function() {}),
			                vastVideoSkippedCallback:(function() {
			                	fpDestroy(playerId` + id + `);
			                	tracking_event_` + id + `("skip"); 
			                	fluidPlayer` + id + `_run = 0; 
		                	}),

			                vastVideoEndedCallback:(function() {
			                	$("#` + id + `").attr("src", videoVAST);
			                	tracking_event_` + id + `("complete"); 
			                	fluidPlayer` + id + `_run = 0;
								setTimeout(function(){
									$("#` + id + `").trigger("pause");
								},1000);	
		                	})
			            }
		            }
		        };

		        var fpDestroy = function(idVideoPlayer) {
	                for (var i = 0; i < fluidPlayerClass.instances.length; i++) {
	                    if (fluidPlayerClass.instances[i].videoPlayerId === idVideoPlayer) {
	                        var videoWrapper = document.getElementById("fluid_video_wrapper_" + idVideoPlayer);
	                        var oldPlayer = document.getElementById(idVideoPlayer);
	                        var newPlayer = oldPlayer.cloneNode(true);
	                        videoWrapper.innerHTML = "";
	                        newPlayer.removeAttribute("src");
	                        videoWrapper.parentNode.replaceChild(newPlayer, videoWrapper);
	                        videoWrapper = null;
	                        oldPlayer = null;

	                        fluidPlayerClass.instances[i] = {videoPlayerId: "83748374hjkehwkfjrweqh8724983278983k"};

	                        break;
	                    } 
	                }
	            }; 

	            var myFP` + id + ` = fluidPlayer(
	                playerId` + id + `,
	                options` + id + `
	             );


		        myFP` + id + `.on("play", function(){
	            	$("#` + id + `_fluid_controls_progress_container").hide();  
	        		$("#skip_button_` + id + `").hide();
	        		tracking_event_` + id + `("resume"); 	
	         	});

		        myFP` + id + `.on("pause", function(){ tracking_event_` + id + `("pause"); });

		        myFP` + id + `.on("theatreModeOn", function(){ tracking_event_` + id + `("fullscreen"); });

		        myFP` + id + `.on("theatreModeOff", function(){ tracking_event_` + id + `("exitfullscreen"); });

				setTimeout(function(){ 
					myFP` + id + `.pause(); 
				},2000);

				var div_position = $("#demo_vid` + id + `").offset();
				var height = $("#demo_vid` + id + `").height();
				var visible_height = height/1.5;
				var first_occuresce = 0;

				var user_pause = 0;

				$(window).scroll(function()
				{
					if(first_occuresce == 0)
					{
						var visible_height_up = div_position.top+(visible_height);
						var screen_height = $(window).height();
						var visible_height_down = (div_position.top+visible_height)-screen_height;


						scroll_position = $(window).scrollTop();

						if(scroll_position >= visible_height_up || scroll_position <= visible_height_down)
						{
							myFP` + id + `.pause();
						} else {
							myFP` + id + `.play();
						}
					}
				});

				$(window).scroll();
			}
			
			
		</script>`
	} else {
		adDetails.Html = ``
	}

}

func AdRenderOutstreamVideoAdSDK(adDetailsFull *AdDetails, zninfo structure.ZoneDetails, r *http.Request) map[string]interface{} {

	var click_url string

	if adDetailsFull.Url != "" {
		click_url = config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + "/ck.php?oaparams=2__bannerid=" + strconv.Itoa(adDetailsFull.Ad_id) + "__campaignid=" + strconv.Itoa(adDetailsFull.Placement_id) + "__zoneid=" + strconv.Itoa(zninfo.Zoneid) + "__oadest=" + adDetailsFull.Url
	}

	imp_url := config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + "/lg.php?bannerid=" + strconv.Itoa(adDetailsFull.Ad_id) + "&amp;campaignid=" + strconv.Itoa(adDetailsFull.Placement_id) + "&amp;zoneid=" + strconv.Itoa(zninfo.Zoneid)

	adDetailsFull.Imp_url = imp_url
	adDetailsFull.Click_url = click_url

	adDetailsFull.Html = vastXml(adDetailsFull, zninfo)
	htmltext := adDetailsFull.Html

	sdk_ad_outs := make(map[string]interface{})

	if zninfo.Vidtype == 1 { // aritcle

		sdk_ad_outs["imp_url"] = imp_url
		sdk_ad_outs["click_url"] = click_url
		sdk_ad_outs["ad_type"] = "IN_ART_VID"
		sdk_ad_outs["ad_tag"] = "NAT_INART"
		sdk_ad_outs["Native_ad"] = OutstreamSDKNv_ad{Ad_type: "IN_ART_VID", Video: htmltext}

	} else if zninfo.Vidtype == 3 { // intertital

		adTag := make(map[string]interface{})
		sdk_ad_outs["imp_url"] = imp_url
		//~ sdk_ad_outs["click_url"] = click_url
		sdk_ad_outs["ad_type"] = "M_INT_VID"
		//~ sdk_ad_outs["HTML_response"] =htmltext
		//~ sdk_ad_outs["layout"] = zninfo.Layout

		adTag["HTML_response"] = htmltext
		adTag["click_url"] = click_url
		adTag["imp_url"] = imp_url
		adTag["layout"] = zninfo.Layout
		adTag["ad_type"] = "M_INT_VID"

		sdk_ad_outs["ad_tag"] = adTag

	} else if zninfo.Vidtype == 4 { // In feed

		Getposition := helper.GetUrlParam(r, "position")

		if Getposition == "true" { // position
			a := make(map[int]interface{})

			position := zninfo.Infeedpos
			repeating := zninfo.Infeedads

			arr := strings.Split(position, ",")

			for key, value := range arr {
				position1 := make(map[string]string)

				position1["position"] = value
				a[key] = position1
			}

			rep := make(map[string]interface{})
			rep["interval"] = repeating

			sdk_ad_outs["repeating"] = rep
			sdk_ad_outs["fixed"] = a

			return sdk_ad_outs

		}

		sdk_ad_outs["imp_url"] = imp_url
		sdk_ad_outs["click_url"] = click_url
		sdk_ad_outs["ad_type"] = "IN_FEED_VID"
		sdk_ad_outs["ad_tag"] = "NAT_FEED"
		sdk_ad_outs["Native_ad"] = OutstreamSDKNv_ad{Ad_type: "IN_FEED_VID",
			Imptracker: []string{click_url},
			Clktracker: click_url,
			Video:      htmltext}

	} else if zninfo.Vidtype == 2 { // native

		Getposition := helper.GetUrlParam(r, "position")

		if Getposition == "true" { // position
			a := make(map[int]interface{})

			position := zninfo.Adposition
			repeating := zninfo.Adinterval

			arr := strings.Split(position, ",")

			for key, value := range arr {
				position1 := make(map[string]string)

				position1["position"] = value
				a[key] = position1
			}

			rep := make(map[string]interface{})
			rep["interval"] = repeating

			sdk_ad_outs["repeating"] = rep
			sdk_ad_outs["fixed"] = a

			return sdk_ad_outs

		}

		ads := make(map[string]interface{})
		Native_ad := make(map[string]interface{})

		var bnrParams map[interface{}]interface{}
		phpserialize.Unmarshal([]byte(adDetailsFull.Parameters), &bnrParams)

		ads["click_url"] = click_url
		ads["imp_url"] = imp_url
		ads["ad_type"] = "M_NAT_VID"
		ads["ad_tag"] = "NAT_CONSTM"

		Native_ad["ad_type"] = "M_NAT_VID"
		Native_ad["title"] = bnrParams["title"].(string)
		Native_ad["ctatext"] = bnrParams["cta_text"].(string)
		Native_ad["iconimage"] = bnrParams["icon_url"].(string)
		Native_ad["mainimage"] = "http://dev.djaxtech.com/DAC069/Videos/3.jpg"
		Native_ad["text"] = bnrParams["text_description"].(string)
		Native_ad["imptracker"] = [1]string{imp_url}
		Native_ad["click_url"] = click_url
		Native_ad["video"] = htmltext
		Native_ad["clktracker"] = ""
		Native_ad["clk"] = ""

		ads["Native_ad"] = Native_ad
		sdk_ad_outs = ads

	} else if zninfo.Vidtype == 6 { // Reward

		rew := strings.Split(zninfo.Reward, "|")
		amt := strings.Split(zninfo.Amount, "|")

		var temp []interface{}
		adTag := make(map[string]interface{})
		rewards := make(map[string]interface{})

		for key, value := range rew {
			ga := make(map[string]string)
			ga["amount"] = amt[key]
			ga["name"] = value
			temp = append(temp, ga)
		}

		sdk_ad_outs["ad_type"] = "REWARDED_VID"

		rewards["rewards"] = temp
		adTag["rewarded_val"] = rewards
		adTag["HTML_response"] = htmltext
		adTag["imp_url"] = imp_url
		adTag["click_url"] = click_url
		adTag["layout"] = zninfo.Layout
		adTag["ad_type"] = "REWARDED_VID"

		sdk_ad_outs["ad_tag"] = adTag

	}

	sdk := make(map[string]interface{})
	sdk["response"] = "success"
	sdk["ads"] = sdk_ad_outs

	return sdk

}

type OutstreamSDKNv_ad struct {
	Ad_type    string   `json:"ad_type,omitempty"`
	Video      string   `json:"video,omitempty"`
	Imptracker []string `json:"imptracker,omitempty"`
	Clktracker string   `json:"clktracker,omitempty"`
}

func vastXml(adDetails *AdDetails, zn structure.ZoneDetails) (xmlresponse string) {

	zoneid := strconv.Itoa(zn.Zoneid)
	adid := strconv.Itoa(adDetails.Ad_id)
	campaign_id := strconv.Itoa(adDetails.Placement_id)
	clickurl := ""
	var video_url, ext_type, video_skip, delivery string

	fcpath := config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/fc.php`

	var bnrParams map[interface{}]interface{}
	phpserialize.Unmarshal([]byte(adDetails.Parameters), &bnrParams)

	if adDetails.Url != "" {
		clickurl = config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/ck.php?oaparams=2__bannerid=` + adid + `__zoneid=` + zoneid + `__cb=7834046c99__oadest=` + adDetails.Url
	}

	logurl := config.GetConfig("protocol", "webpath") + config.GetConfig("delivery", "webpath") + `/lg.php?bannerid=` + adid + `&campaignid=` + campaign_id + `&zoneid=` + zoneid

	if bnrParams["vid_upload_type"] == "External" {
		video_url = bnrParams["video_url"].(string)
	} else if bnrParams["vid_upload_type"] == "Internal" {
		video_url = config.GetConfig("protocol", "webpath") + config.GetConfig("images", "webpath") + "/" + bnrParams["rm_video"].(string)
	} else {
		video_url = config.GetConfig("protocol", "webpath") + config.GetConfig("admin", "webpath") + `/plugins/Outstream/delivery/js/videoplayback.mp4`
	}

	if bnrParams["extension_type"] != "HLS" {
		delivery = "progressive"
		ext_type = "video/mp4"

	} else {
		delivery = "streaming"
		ext_type = "application/x-mpegURL"
	}

	if bnrParams["skip"].(string) != "" {
		video_skip = bnrParams["skip"].(string)

	} else {
		video_skip = "00:00:30"
	}

	if bnrParams["vid_type"] == "Internal" {
		xmlresponse = `<?xml version="1.0" encoding="UTF-8"?><VAST version="3.0"><configuration><system.webServer><httpProtocol><customHeaders><add name="Access-Control-Allow-Origin"/></customHeaders></httpProtocol></system.webServer></configuration><Ad id="` + zoneid + `"><InLine><AdSystem><![CDATA[Reviveadservermod.com]]></AdSystem><AdTitle><![CDATA[Vast 3.0]]></AdTitle><Pricing><model><![CDATA[CPM]]></model><currency><![CDATA[USD]]></currency></Pricing><Impression><![CDATA[` + logurl + `]]></Impression><Creatives><Creative><Linear skipoffset="` + video_skip + `"><TrackingEvents><Tracking event="start"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=start]]></Tracking><Tracking event="firstQuartile"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=firstquartile]]></Tracking><Tracking event="midpoint"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=midpoint]]></Tracking><Tracking event="thirdQuartile"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=thirdquartile]]></Tracking><Tracking event="complete"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=complete]]></Tracking><Tracking event="pause"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=pause]]></Tracking><Tracking event="mute"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=mute]]></Tracking><Tracking event="fullscreen"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=fullscreen]]></Tracking><Tracking event="unmute"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=unmute]]></Tracking><Tracking event="closeLinear"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=closeLinear]]></Tracking><Tracking event="acceptInvitationLinear"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=acceptInvitationLinear]]></Tracking><Tracking event="skip"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=skip]]></Tracking><Tracking event="progress" offset="00:00:10"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=progress]]></Tracking><Tracking event="exitFullscreen"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=exitfullscreen]]></Tracking><Tracking event="rewind"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=rewind]]></Tracking><Tracking event="resume"><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=resume]]></Tracking></TrackingEvents><VideoClicks><ClickThrough>` + clickurl + `</ClickThrough></VideoClicks><MediaFiles><MediaFile delivery="` + delivery + `" bitrate="400" width="640" height="480" type="` + ext_type + `" scalable="true" maintainAspectRatio="true"><![CDATA[` + video_url + `]]></MediaFile></MediaFiles></Linear></Creative></Creatives></InLine></Ad></VAST>`
	} else if bnrParams["vid_type"] == "External" {
		xmlresponse = `<VAST xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' version='3.0' xsi:noNamespaceSchemaLocation='vast.xsd'><Ad id='` + zoneid + `'><Wrapper><AdSystem><![CDATA[ Revive Adserver ]]></AdSystem><AdTitle><![CDATA[ inline thirdparty ]]></AdTitle><Impression><![CDATA[` + logurl + `]]></Impression><VASTAdTagURI><![CDATA[` + video_url + `]]></VASTAdTagURI><Creatives><Creative><Linear><Duration/><TrackingEvents><Tracking event='start'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=start]]></Tracking><Tracking event='firstQuartile'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=firstquartile]]></Tracking><Tracking event='midpoint'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=midpoint]]></Tracking><Tracking event='thirdQuartile'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=6&event=thirdquartile]]></Tracking><Tracking event='complete'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=complete]]></Tracking><Tracking event='pause'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=pause]]></Tracking><Tracking event='mute'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=mute]]></Tracking><Tracking event='fullscreen'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=fullscreen]]></Tracking><Tracking event='unmute'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=unmute]]></Tracking><Tracking event='creativeView'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=creativeView]]></Tracking><Tracking event='acceptInvitationLinear'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=acceptInvitationLinear]]></Tracking><Tracking event='closeLinear'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=closeLinear]]></Tracking><Tracking event='skip'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=skip]]></Tracking><Tracking event='progress'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=progress]]></Tracking><Tracking event='exitFullscreen'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=exitfullscreen]]></Tracking><Tracking event='rewind'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=rewind]]></Tracking><Tracking event='resume'><![CDATA[` + fcpath + `?script=rmvideoAds:rmvastEvent&bannerid=` + adid + `&zoneid=` + zoneid + `&event=resume]]></Tracking></TrackingEvents>` + clickurl + `</Linear></Creative></Creatives></Wrapper></Ad></VAST>`
	} else {
		xmlresponse = ``
	}

	return xmlresponse
}
