var findTag = "prem=y"; 
var findCookie = "UID";
var redirectUrl = "http://www.philly.com/s?action=reg&requested=y&note=video&rurl="+document.location;

var bcExp;
var modVP;
var modExp;
var modCon;


var bc_playList = new Array()
bc_playList["g=news"] = "News";
bc_playList["g=sports"] = "Sports";
bc_playList["g=gossip"] = "Gossip";
bc_playList["g=pbt"] = "Philadelphia Business Today";
bc_playList["g=uncorked"] = "Philly Uncorked";
bc_playList["g=down-the-shore"] = "Down The Shore";
bc_playList["g=gardener-studio"] = "Gardener's Studio";
bc_playList["g=philly-dish"] = "The Philly Dish" ;
bc_playList["g=mob-scene"] = "Mob Scene";
bc_playList["g=snapglowtv"] = "SnapGlowTV";


var find_video_method="find_videos_by_tags";
var bc_video_per_page=10;
var bc_video_count=0;
var bc_containerID="";
var bc_tag="news";

function loadPlayer(videoID, videoAutoStart) {

	var bc_params = {};
	bc_params["id"] = "myExperience";
	bc_params["bgcolor"] = "#FFFFFF";
	bc_params["width"] = 620;
	bc_params["height"] = 403;
	bc_params["playerId"] = 21394218001;
	bc_params["publisherID"] = 20779451001;

	bc_params["@videoPlayer"] = videoID;

	var pHtml = "\n\n<!-- Start Brightcove Player -->";
	pHtml += "\n<object id=\"myExperience\" class=\"BrightcoveExperience\">";
	pHtml += "\n<param name=\"bgcolor\" value=\"" + bc_params["bgcolor"] + "\" />";
	pHtml += "\n<param name=\"width\" value=\"" + bc_params["width"] + "\" />";
	pHtml += "\n<param name=\"height\" value=\"" + bc_params["height"] + "\" />";
	pHtml += "\n<param name=\"playerID\" value=\"" + bc_params["playerId"] + "\" />";

	// Start Assigning Programming
	if(bc_params["@videoPlayer"] != null) {
		pHtml += "\n<param name=\"@videoPlayer\" value=\"" + bc_params["@videoPlayer"] + "\" />";
	} else if(bc_params["@playlistTabs"] != null) {
		pHtml += "\n<param name=\"@playlistTabs\" value=\"" + bc_params["@playlistTabs"] + "\" />";
		if(bc_params["@playlistTabs.featured"] != null) { pHtml += "\n<param name=\"@playlistTabs.featured\" value=\"" + bc_params["@playlistTabs.featured"] + "\" />"; }
		if(bc_params["@videoList.featured"] != null) { pHtml += "\n<param name=\"@videoList.featured\" value=\"" + bc_params["@videoList.featured"] + "\" />"; }
	}
	// End Assigning Programming


	pHtml += "\n<param name=\"linkBaseURL\" value=\"" + buildVideoLink(videoID) + "\" />";
	pHtml += "\n<param name=\"autoStart\" value=\""+videoAutoStart+"\" />";
	pHtml += "\n<param name=\"isVid\" value=\"true\" />";
	pHtml += "\n<param name=\"isUI\" value=\"true\" />";
	pHtml += "\n</object>";
	pHtml += "\n<!-- End Brightcove Player -->\n\n";
	document.getElementById("bcPlayer").innerHTML = pHtml;

	brightcove.createExperiences('0', 'myExperience');
	
}

/////// building video link for linkBaseURL //////
function buildVideoLink(videoID) {
	var vidUrl;
	var currentLink = window.location.href;
 	// Get the current URL and remove any existing URL parameter
	if(currentLink.indexOf("?") != -1) {
		currentLink = currentLink.substring(0,currentLink.indexOf("?"));
	}
	
	// vidUrl = currentLink + "?vid=" + videoID;
	vidUrl = currentLink;
	return vidUrl;
}


// called when template loads, this function stores a reference to the player and modules.
// Then event listeners will be added for when the template is ready and when a user
// clicks on a video.
function onTemplateLoaded(experienceID) {
    //alert("EVENT: TEMPLATE_LOAD");

    bcExp = brightcove.getExperience(experienceID);

    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);
    modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modCon = bcExp.getModule(APIModules.CONTENT);
    modMenu = bcExp.getModule(APIModules.MENU);

    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, onContentLoad);
    modCon.addEventListener(BCContentEvent.VIDEO_LOAD, onVideoLoad);
    modMenu.addEventListener(BCMenuEvent.VIDEO_REQUEST, onMenuContentLoad);
    modVP.addEventListener(BCMediaEvent.BEGIN, onMediaBegin);

}
function onTemplateReady(evt) {
    //alert("EVENT: TEMPLATE_READY");
    }
function onContentLoad(evt) {
    //alert("EVENT: CONTENT_LOAD");

    var currentVideo = modVP.getCurrentVideo();
    //alert("INFO: Currently Loaded videoID: " + currentVideo.id );

    var currentMedia = modCon.getMedia(currentVideo.id);
    //alert("INFO: " + currentMedia.displayName + "-" + currentMedia.shortDescription);

    document.getElementById("bcPlayer-VideoTitle").innerHTML = currentMedia.displayName;
    document.getElementById("bcPlayer-VideoShortDescription").innerHTML = currentMedia.shortDescription;
    document.getElementById("bcPlayer-VideoID").innerHTML = currentVideo.id;
    
    //function LoadAds(adposID", adSite, adZone, adOrd, adChannel, adCategories, adMiscTag)
    var adKeys = readAdKeys(currentMedia.adKeys); // adKeys=;aspect=16_9;chan=business;show=pbt
    var adChannel = adKeys["chan"];
    var adShow = adKeys["show"];
    //alert ("adChannel: " + adChannel);
    if (adChannel==undefined) { adChannel = 'news'; }
    LoadAds('mrec_300x250', 'homepage', adChannel, '', adChannel, '', adShow);

    modCon.getMediaAsynch(currentVideo.id);
}
function onMenuContentLoad(evt) {
    //alert("EVENT: MENU VIDEO_REQUEST");
    
    var currentMedia = evt["args"];

    document.getElementById("bcPlayer-VideoTitle").innerHTML = currentMedia.displayName;
    document.getElementById("bcPlayer-VideoShortDescription").innerHTML = currentMedia.shortDescription;
    document.getElementById("bcPlayer-VideoID").innerHTML = currentMedia.id;
    
    //function LoadAds(adposID", adSite, adZone, adOrd, adChannel, adCategories, adMiscTag)
    var adKeys = readAdKeys(currentMedia.adKeys); // adKeys=;aspect=16_9;chan=business;show=pbt
    var adChannel = adKeys["chan"];
    var adShow = adKeys["show"];
    //alert ("adChannel: " + adChannel);
    if (adChannel==undefined) { adChannel = 'news'; }
    LoadAds('mrec_300x250', 'homepage', adChannel, '', adChannel, '', adShow);


}

function onMediaBegin(evt) {
	// alert("EVENT: MEDIA_BEGIN " + evt["media"]["id"]);
	for(prop in evt["media"]["tags"]) {
		var myTag = evt["media"]["tags"][prop]["name"];
		if (myTag==findTag) {
			if (chkSubscription(findCookie)==false) {
				//document.location = redirectUrl + "&vid=" + evt["media"]["id"];
				window.location.href = redirectUrl + "&vid=" + evt["media"]["id"];
			}
		}
	}
}

function chkSubscription(coo) {
	var subKey = readCookie(coo);
	if ( (subKey==null) || (subKey=='') ) {
		return (false);
	} else {
		return (true);
	}
} 

function onVideoLoad(evt) {
    //alert("EVENT: VIDEO_LOAD");
    // Play video that was just loaded
    modVP.loadVideo(evt.video.id);
}

function readAdKeys(ak) {
	var adKeyValue = new Object();
	var adKeys = new Object();

	if (ak.length<1) { return false; }

	var numKey = 1;
	while (ak.indexOf(';') > -1) {
		adKeys[numKey] = ak.substring(0,ak.indexOf(';'));
		ak = ak.substring(ak.indexOf(';')+1);
		numKey++;
	}
	adKeys[numKey] = ak;
	for (ii in adKeys) {
		keyName = adKeys[ii].substring(0, adKeys[ii].indexOf('='));
		keyValue = adKeys[ii].substring(adKeys[ii].indexOf('=')+1);
		adKeyValue[keyName] = keyValue;
	}

	return(adKeyValue);
}


        // Our callback loops through the returned videos, alerting their names.
        function showItems (response) {
        	
        	//alert("pg no:" + response.page_number + "|pg sz:" + response.page_size + "|tt cnt:" + response.total_count);
        	//alert("item cnt:" + response.items.length);
		bc_video_count=response.total_count;
		var pg = 0;
		if ((typeof response.page_number)!="undefined") { pg = parseInt(response.page_number); }
		
                var s = "";
                for (var ii=0;ii<response.items.length;ii++) {
                	var video = response.items[ii];
                	var video_url = "?vid=" +video.id+ "&pg=" +pg+ "&tg=" +bc_tag;
                	s += "<div class='bc_lineupThumb' onMouseOver=\"this.className='bc_lineupThumb2'\" onMouseOut=\"this.className='bc_lineupThumb'\" >";
                	s += "<div id='bc_" +video.id+ "_lineupThumb' class='bc_ct_lineupThumb' onClick='loadPlayer(\""+video.id+"\", \"true\")' >";
                	s += "<img src='" +video.thumbnailURL+ "' width='104' height='78' style='border:2px solid #666666;cursor:pointer;'>";
                	s += "</div>";
                	s += "<div>" +video.name.replace(/_/g," ")+ "</div>";
                	s += "</div>";
                }
		
                // paging container
		s += "<div class='aVideoPaging'>";
		
		var genreLink = "/philly/video/VideoArchive.html?vgenre=" + cpt1(bc_tag.replace("g=",""));
		if ((typeof bc_playList[bc_tag])!="undefined") {
			genreLink = "/philly/video/VideoArchive.html?vgenre=" + bc_playList[bc_tag];
		}
		
		s += "<div style='width:80px;' id='videoViewAllButton' class='aVideoPagingNext' onClick='document.location.href=\""+genreLink+"\"'";
		s += " onMouseOver=\"this.className='aVideoPagingNexto'\" onMouseOut=\"this.className='aVideoPagingNext'\">VIEW ALL</div>";
		
		if (pg<Math.floor(bc_video_count/bc_video_per_page)) {
			var pageNext = parseInt(pg)+1;
			s += "<div class='aVideoPagingNext' onClick='bc_page(\""+bc_containerID+"\",\""+bc_tag+"\"," +pageNext.toString()+ ");'";
			s += " onMouseOver=\"this.className='aVideoPagingNexto'\" onMouseOut=\"this.className='aVideoPagingNext'\">NEXT</div>";
		} else {
			//s += "<div class='aVideoPagingNext' onClick=''";
			//s += " onMouseOver='' onMouseOut=''>NEXT</div>";
		}
		
		if (pg>0) {
			var pagePrev = parseInt(pg)-1;
			s += "<div class='aVideoPagingPrev' onClick='bc_page(\""+bc_containerID+"\",\""+bc_tag+"\"," +pagePrev.toString()+ ");'";
			s += " onMouseOver=\"this.className='aVideoPagingPrevo'\" onMouseOut=\"this.className='aVideoPagingPrev'\">PREV</div>";
		} else {
			//s += "<div class='aVideoPagingPrev' onClick=''";
			//s += " onMouseOver='' onMouseOut=''>PREV</div>";
		}
		

		
		s += "</div>";
		s += "<div class='divclear'></div>";
                
                document.getElementById(bc_containerID).innerHTML = s;
        }
        
        function showPlaylist (response) {
	                var s = "";
	                for (var ii=0;ii<response.items.length;ii++) {
	                	var item = response.items[ii];
				s += '<dt class="rlinks_colorbar1"> <div class="b_sq"> </div><a href="#_self" class="bl"><b>' + item.name + '</b> </a></dt>';
	                }
	                
	                document.getElementById("bc_playlists").innerHTML = s;
        }
        
        function bc_page(cid, ctag, vpg) {
        	bc_containerID = cid;
        	bc_tag = ctag;
		kudos.get(find_video_method, {"callback":"showItems","and_tags":bc_tag,"video_fields":"id,name,thumbnailURL","page_size":bc_video_per_page,"page_number":vpg,"get_item_count":"true","sort_by":"MODIFIED_DATE","sort_order":"DESC"});
        }
	
	function cpt1(iStr) {
		var wo = iStr.split(" ");
		for (x=0; x<wo.length; x++) {
			wo[x] = wo[x].substring(0, 1).toUpperCase()+wo[x].substring(1);
		};
		iStr = wo.join(" ");
		return(iStr);
	};
	
	function SaveAndShare (shareSite) {
	
		var siteURL;
		var videoURL = "http://www.philly.com/philly/video/?vid=" + document.getElementById("bcPlayer-VideoID").innerHTML;
		var videoTitle = document.getElementById("bcPlayer-VideoTitle").innerHTML; 
		var videoDesc = document.getElementById("bcPlayer-VideoShortDescription").innerHTML;
		
		switch(shareSite) {
		case "facebook":
			//siteURL = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(videoURL) + "&t=" + encodeURIComponent(videoTitle) ;
			//siteURL = "http://www.facebook.com/sharer.php?u=" + videoURL + "&t=" + videoTitle ;
			siteURL = 'http://fb-share-control.com?u='+encodeURIComponent(videoURL)+'&amp;t='+encodeURIComponent(videoTitle)+'&amp;i=&amp;d='+encodeURIComponent(videoDesc);
			break;
		case "digg":
			siteURL = "http://digg.com/submit?phase=2&url=" + encodeURIComponent(videoURL) + "&title=" + encodeURIComponent(videoTitle) + "&bodytext=" + encodeURIComponent(videoDesc) + "&media=video";
			break;
		case "delicious":
			siteURL = "http://del.icio.us/post?v=4&partner=philly&noui&jump=close&url=" + encodeURIComponent(videoURL) + "&title=" + encodeURIComponent(videoTitle) + "&notes=" + encodeURIComponent(videoDesc);
			break;
		case "buzz":
			//siteURL = "http://digg.com/submit?phase=2&url=" + videoURL + "%3referrer=philly&title=" + videoTitle + "&bodytext=" + videoDesc;
			break;
		case "yahoo":
			//siteURL = "http://myweb2.search.yahoo.com/myresults/bookmarklet?u=" + encodeURIComponent(videoURL) + "&title=" + encodeURIComponent(videoTitle);
			siteURL = "http://myweb2.search.yahoo.com/myresults/bookmarklet?u=" + videoURL + "&t=" + videoTitle + "&d=" + videoDesc;
			break;
		case "google":
			siteURL = "http://www.google.com/bookmarks/mark?op=add&bkmk=" + encodeURIComponent(videoURL) + "&title=" + encodeURIComponent(videoTitle) + "&annotation=" + encodeURIComponent(videoDesc);
			break;
		case "reddit":
			siteURL = "http://reddit.com/submit?url=" + encodeURIComponent(videoURL) + "&title=" + encodeURIComponent(videoTitle) ;
			break;
		case "furl":
			//siteURL = "http://www.furl.net/storeIt.jsp?u=" + encodeURIComponent(videoURL) + "&t=" + encodeURIComponent(videoTitle) ;
			siteURL = "http://www.diigo.com/post?url=" + videoURL + "&title=" + videoTitle + "&description=" + videoDesc;
			break;
		case "philly":
			break;
		default:
			//code to be executed if n is different from case 1 and 2
		}
	
		// alert(siteURL);
		window.open(siteURL,'SaveAndShare');
		return false;
	}

//Generic search video, mostviewed…etc.
function searchVideo(s, pn, pz){
	var svideo_id = document.getElementById("bcPlayer-VideoID").innerHTML ;
	alert(s + ' = query/cmd ; DEBUG page# ' + pn + ' ; vid='+svideo_id) ;
	squery = s; 
	spage_number = pn ;
	spage_size = pz ;
	
	if(s == null || s.length  == 0){
		alert('Missing required search term ' + squery) ;
		document.sVideo.txtVideoSearch.focus() ;
		return false ;		
	}else {
		if(s == 'MOST_VIEWED'){
			var isKudos = kudos.get("find_all_videos", {"callback":"SearchShowItems","video_fields":"id,name,thumbnailURL,shortDescription","page_size":spage_size,"page_number":spage_number,"get_item_count":"true","sort_by":"plays_total"});
		}else if(s == 'RELATED_VIDEOS'){			
			var isKudos = kudos.get("find_related_videos", {"callback":"SearchShowItems","video_fields":"id,name,thumbnailURL,shortDescription","page_size":spage_size,"page_number":spage_number,"get_item_count":"true","video_id":svideo_id});		
		}else {
			var isKudos = kudos.get("find_videos_by_text", {"callback":"SearchShowItems","video_fields":"id,name,thumbnailURL,shortDescription","text":squery, "page_size":spage_size,"page_number":spage_number,"get_item_count":"true"});		
		}
	}
}       
			 			 		
//display for searchVideo
function SearchShowItems (response) {
        	
        	//alert("pg no:" + response.page_number + "|pg sz:" + response.page_size + "|tt cnt:" + response.total_count);
        	//alert("item cnt:" + response.items.length);
								
		bc_video_count=response.total_count;
		var pg = 0;
		if ((typeof response.page_number)!="undefined") { pg = parseInt(response.page_number); }
				
                var s = "";
                for (var ii=0;ii<response.items.length;ii++) {
                	var video = response.items[ii];
                	var video_url = "?vid=" +video.id+ "&pg=" +pg+ "&tg=" +bc_tag;
                	s += "<div class='bc_lineupThumb' onMouseOver=\"this.className='bc_lineupThumb2'\" onMouseOut=\"this.className='bc_lineupThumb'\" >";
                	s += "<div id='bc_" +video.id+ "_lineupThumb' class='bc_ct_lineupThumb' onClick='loadPlayer(\""+video.id+"\", \"true\")' >";
                	s += "<img src='" +video.thumbnailURL+ "' width='104' height='78' style='border:2px solid #666666;cursor:pointer;'>";
                	s += "</div>";
                	s += "<div>" +video.name.replace(/_/g," ")+ "</div>";
                	s += "</div>";
                }
		
        // paging container / HUNG TEST
		//onClick="searchVideo(document.sVideo.txtVideoSearch.value, 0); return false;"
        if ((typeof response.page_size)!="undefined") { pz = parseInt(response.page_size); }			
		s += "<div class='aVideoPaging'>";
		
		//alert('SEARCH TEXT = '+squery) ;

		//NEXT
		var pnext = pg + 1 ;
		if(bc_video_count > (pz*pnext)){		
								
			//alert(bc_video_count + ':tt > totalNEXT : '+(pz*(pnext)) + '; NEXT PAGE = ' + pnext) ;
			s += "<div class='aVideoPagingNext' onClick='searchVideo(\""+squery+"\","+ pnext +","+ pz +"); return false;'";
			s += " onMouseOver=\"this.className='aVideoPagingNexto'\" onMouseOut=\"this.className='aVideoPagingNext'\">NEXT</div>";	
		}
		
		//PREV
		if(pg > 0){
			var pprev = pg - 1 ;
			//alert(squery + ' : PREV PAGE = '+ pprev) ;
			s += "<div class='aVideoPagingPrev' onClick='searchVideo(\""+squery+"\","+pprev+","+ pz+ "); return false;'";
			s += " onMouseOver=\"this.className='aVideoPagingPrevo'\" onMouseOut=\"this.className='aVideoPagingPrev'\">PREV</div>";
		}
				
		s += "</div>";
		s += "<div class='divclear'></div>";
                
        document.getElementById(bc_containerID).innerHTML = s;
				
    }
