/*** FLASH COMMUNICATION INTERFACE *****/
function getFlashMovie(movieName){
    var isIE = navigator.appName.indexOf("Microsoft") != -1;
    return (isIE) ? window[movieName] : document[movieName];
}
function passPlaylistSelection(x){
    var videoID = x;
    document["videoplayer"].sendvideoIDToFlash(videoID);
}
/*
 * //Custom function which incorporates video tracking in omniture 
function passPlaylistSelection(x, n){
    s_video = n;
    //void (s.t()); // enable this line if omniture tracking code is included to page (groupsite tracking js file - om_group.js)
    var videoID = x;
    document["videoplayer"].sendvideoIDToFlash(videoID);
}
*/
function getTextFromFlash(str){
    document.htmlForm.receivedField.value = "From Flash: " + str;
    return str + " received";
}
/*** FLASH COMMUNICATION INTERFACE *****/


 $(document).ready(function(){
 			
     $("#vPlayerPlaylistDATA").load("playlists.html", function(){
	 	if (debug == 1)
		console.log("playlists.htlm loaded");
         if (channel != null && video != null) {
             $loadChannels(channel, video);
         }
         else 
             //load default channel
             $loadChannels(0, 0);
         setTimeout(function(){
             $("#vPlayer").show();
             setTimeout(function(){
                 $getPopularItems();
             }, 7000);
         }, 1600);
     });
            var channel = $(this).getUrlParam("ch");
			var video = $(this).getUrlParam("v");
			var debug = $(this).getUrlParam("debug");
			
            if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
                try { document.execCommand("BackgroundImageCache", false, true); }
                catch (err) {
                }
            }

        /*    $("div.c_scrollable").scrollable({
                vertical: true,
                prev: '.c_prev',
                next: '.c_next',
                navi: '.c_navi',
                activeClass: 'c_active'
            });
            
            $("div.scrollable").scrollable(); */
			var api_V = $("div.c_scrollable").scrollable({
                  vertical: true,
                  prev: '.c_prev',
                  next: '.c_next',
                  navi: '.c_navi',
                  activeClass: 'c_active',
                  size: 7,
                  api:true
            });

           var api_H = $("div.scrollable").scrollable({
                  size: 4,
                  api:true
            });

            
           $loadChannels = function(activeIndex,videoIndex) {
                var items = $("div.c_scrollable");
                // get handle to scrollable api 
                var api = $("div.c_scrollable").scrollable();
                
                //ajax load channels html from playlists.html
                //and callback set to append channels
                $("#channelsonstandby").empty().append($("#vPlayerPlaylistDATA #channels div").clone());
				 setTimeout(function(){
                    api.getItems().remove();
					//alert($("#channelsonstandby div"));
                    api.getItemWrap().append($("#channelsonstandby div"));
                    // rebuild scrollable 
                    api.reload().begin();
                    setTimeout(function(){
                        items.slideDown("slow", function(){
                            api.click(activeIndex);
                            setTimeout(function(){
                                $updatePlaylist($(".c_scrollable .items .c_active").attr("id"), videoIndex);
                                items = null;
                                api = null;
                                $(".c_scrollable .items div").click(function(){
                                    $updatePlaylist($(this).attr("id"), 0);
                                })
                            }, 200);
                        });
                    }, 800)
                }, 200);
            }
            
            $updatePlaylist = function (playlistID,activeIndex){
                var items = $("div.scrollable");
				items.hide();
				$("#video_url").hide();
				$("#video_title, #video_info").hide();
                // get handle to scrollable api 
                var api = items.scrollable();
                
                //ajax load playlist html from playlists.html
                //and callback set to append new list
                $("#listonstandby").empty().append($("#vPlayerPlaylistDATA #" + playlistID + " div.vlink").clone());
				setTimeout(function(){
                    api.getItems().remove();
                    api.getItemWrap().append($("#listonstandby div.vlink"));
                    // rebuild scrollable   
                    api.reload().begin();
                    setTimeout(function(){
                        $("#videoinfoonstandby").empty().append($("#vPlayerPlaylistDATA ." + playlistID + " div.vinfo").clone());//load("playlists.html ." + playlistID + " div.vinfo", function(){
							setTimeout(function() {
							if (debug==1)
							console.log("playlists.html for Popular loaded");
                            items.show("slow", function() {
							$updateTitle(activeIndex);
							//$updateVideoInfo(activeIndex);
							setTimeout(function() {
								passPlaylistSelection($getVideoID(activeIndex));
								items = null;
								api.click(activeIndex);
                    			api = null;
							},800);
                        });
						},200);
                    },800);
                }, 200);
            }
			
			$updateTitle = function(activeIndex) {
				var title = $(".vlink a:eq("+activeIndex+")",$(".scrollable")).text();
				if(debug == 1)
					console.log("Video Title: " + title);
				$("#video_title").text(title);
				setTimeout(function() {
					$("#video_title").slideDown("fast", function() {
						$updateVideoInfo(activeIndex);
					});
				},800);
				title=null;
			}
			
			$updateVideoInfo = function(activeIndex) {
				var info = $(".vinfo:eq("+activeIndex+")").html()
				$("#video_info").empty().html(info);
				setTimeout(function() {
					$("#video_info").slideDown("fast",function() {
						$("#sURL").text($getShareURL());
						$("#video_url").show("slow");
					});
				},800);
				info=null;
			}
			
			$getActiveItem = function() {
				return $("div.scrollable div.items div.vlink").index($(".active"));
			}
			
			$getActiveItemLang = function() {
				var classlang = $("div.scrollable div.items div.active").attr("class");
				if(debug == 1) {
					console.log("Language: "+classlang.substr(classlang.indexOf("lang:")+5,2));
					console.log("lang search: "+ classlang.search(/lang:/));
					}
				if(classlang.search(/lang:/)==-1)
					return undefined;
				else
					return classlang.substr(classlang.indexOf("lang:")+5,2);
			}
			
			$getActiveChannel = function(){
				return $("div.c_scrollable div.items div.channel").index($(".c_active"));
			}
					
			$getPopularItemChannel = function(id) {
				return $("div.c_scrollable div.items div.channel").index($(".channel[id='"+id+"']"));
			}
			
			$getShareURL = function() {
				var currentChannel = $getActiveChannel();
				var currentCurrentVideo = $getActiveItem();
				var url = window.location.href;
				var urlhref = null;
				var lang = null;
				if(url.indexOf("?")<0) {
					urlhref = url;
				}
				else
				urlhref = url.substring(0,url.indexOf("?"));
				if(debug == 1)
					console.log($getActiveItemLang());
				lang = $getActiveItemLang();
				if(lang == undefined)
					return(urlhref+"?ch="+currentChannel+"&v="+currentCurrentVideo);
				else
					return(urlhref+"?ch="+currentChannel+"&v="+currentCurrentVideo+"&lang="+lang);
			}
			
			$getVideoID = function(activeIndex) {
				var href= null;
				href = $(".vlink a:eq(" + activeIndex + ")",$(".scrollable")).attr("href");
				if(debug == 1)
				console.log("Element clicked: " +$(".vlink a:eq(" + activeIndex + ")",$(".scrollable")));
				if(debug == 1)
				console.log("Element clicked href: "+'Checked href attr: '+ href);
				return href.substring(href.lastIndexOf("(") + 1, href.lastIndexOf(")"));
			}
					
			$getPopularItems = function() {
				$("#vPopular").empty().load("playlists.html .playlist", function(){
					$(".vpop",this).each(function() {
						var playlistID = $(this).parent().attr("id");
						var channelIndex = $getPopularItemChannel(playlistID);
						var href = $("a",this).attr("href");
						var itemIndex = $(".vlink, .vpop",$("#"+playlistID)).index(this);//href.substring(href.lastIndexOf("(") + 1, href.lastIndexOf(")"));
						if(debug == 1)
							console.log(itemIndex)
						$("a",this).attr("href","javascript:$loadChannels("+channelIndex+","+itemIndex+");");
					});
					$(".playlist",this).slideDown();
					$(".vpop",this).removeClass("vlink");
				})
			}    
            
           	$("html").click(function(e){
					var target = $(e.target);
					if(debug == 1)
						console.log($(e.target));
					var activeIndex = null;
					var videoID = null;
					if (target.parent().hasClass("vlink") || target.hasClass("vlink")) {
						if (debug == 1) 
						console.log("vlink");
						$("#video_title, #video_info, #video_url").slideUp(500);
						setTimeout(function() {
							activeIndex = $getActiveItem();
							if (debug == 1) 
								console.log('Clicked on ACTIVEINDEX:' + activeIndex);
							setTimeout(function(){
								videoID = $getVideoID(activeIndex);
								if (debug == 1) 
									console.log('After click - fetched video VIDEOID:' + videoID);
								$updateTitle(activeIndex);
								setTimeout(function(){
									passPlaylistSelection(videoID);
								}, 300);
							}, 800)
						},510);
					}
				});
        });
