var cid; //clip id
var pid; //video package id
var videourl; //for fb+twitter buttons
var clipurl; //clip url input box
var episodeurl; //episode url input box
var offset=0;
var numcomments=0;
var like = 1;
var autolike = 0;
var artistname="";
function SendVideoInfo(){
	
	cid="";
	pid="";
	if (VideoInfo.category=="ad"){
		$("#VideoComponentsWrapper").hide();
		try{ toggleErrorReporting(); } catch(err) {}		
	}
	if (VideoInfo.category!="ad"){
		$("#VideoComponents").show();
		$("#VideoComponentsWrapper").show();
		try{ toggleErrorReporting(); } catch(err) {}		
	}
	$("#episodeurl").hide();
	$("#videoembed").hide();
	closeVideoShare();
	closeVideoComments();
	//if only a clip id is sent
	if (VideoInfo.eid==""||VideoInfo.eid==undefined){
		videourl=baseurl+"cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.title);
		clipurl=baseurl+"cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.title);
		commenturl=baseurl+videourl; //for comment engine linkback
		cid=VideoInfo.id;
		unit_id=cid;
	//if a video package + clip id is sent
	} else {
		clipurl=baseurl+"cid/"+VideoInfo.id+"/pid/"+VideoInfo.eid+"/"+sluggify(VideoInfo.title);
		episodeurl=baseurl+"pid/"+VideoInfo.eid+"/";	
		
		//if it's a music video link fb+twitter to clip in package
		if (LinkToClip==1){
			videourl="cid/"+VideoInfo.id+"/pid/"+VideoInfo.eid+"/"+sluggify(VideoInfo.title);
		//link to just cid, use for music videos playlists
		} else if(LinkToClip==2){
			if(VideoInfo.artist==null||VideoInfo.artist==""){
				clipurl=baseurl+"cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.title);
				videourl="cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.title);	
				
			} else{
				clipurl=baseurl+"cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.artist)+"-"+sluggify(VideoInfo.title);
				videourl="cid/"+VideoInfo.id+"/"+sluggify(VideoInfo.artist)+"-"+sluggify(VideoInfo.title);	
			}
			
			$("#episodeurl label").html("Playlist URL");
		//if it's not a music video just link to package	
		}else{
			videourl="pid/"+VideoInfo.eid+"/";	
		}	
		commenturl=baseurl+videourl; // for comment engine linkback
		cid=VideoInfo.id;
		pid=VideoInfo.eid;
		
		if (unit_type=="clipid"){
			unit_id=cid;
		} else{
			unit_id=pid;
		}
	}
	
	if (LinkToClip==1||LinkToClip==2){
		if(VideoInfo.artist==null||VideoInfo.artist==""){
			document.title=VideoInfo.title;
			
		} else {
			document.title=VideoInfo.artist+" - "+VideoInfo.title;
		}
		
	} else {
		document.title=VideoInfo.title;
	}
	$("#clipurl input").attr("value",clipurl);

	//FB Like+Share Button
	$("#FBShareVC").html('<div class="fb-send" data-href="'+baseurl+videourl+'" data-font="arial"></div>');
	$("#FBLikeVC").html('<fb:like href="'+baseurl+videourl+'"width="80" layout="button_count"></fb:like>');
	FB.XFBML.parse(document.getElementById("FBLikeVC"));
	FB.XFBML.parse(document.getElementById("FBShareVC"));
	
	//Twitter	
	$("#TweetButtonVC").html('<a href="http://twitter.com/share" class="twitter-share-button" data-url="'+baseurl+videourl+'" data-count="horizontal" data-text="I\'m watching '+document.title+' on MuchMusic.com'+' ">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></scri'+'pt>');
	
	//Googleplus
	$("#GooglePlusVC").html('<div class="g-plusone" data-size="medium" data-href="'+baseurl+videourl+'"></div>');
	gapi.plusone.go();
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
	   var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
	   if (ieversion==7){
	   		$("#GooglePlusVC").hide(); 	
	   }
	} 
	getLikeCount();
	hasUserLiked();
}

function sluggify(str) {
  str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  str = str.replace(/[^a-z0-9 ]/g, '') // remove invalid chars
	.replace(/\s+/g, '-') // collapse whitespace and replace by -
	.replace(/-+/g, '-'); // collapse dashes

  return str;
}
function copyclip(value){
	var clipcopy = new ZeroClipboard.Client();
	clipcopy.setText(value);
	clipcopy.glue('clipsharecopy');
	clipcopy.addEventListener('complete', function(client, value) {
		//alert("Copied text to clipboard:\n" + value);
		$("#clipurl input").attr("value","URL added to clipboard");
		$("#clipurl input").css("color","#ff0000");
		//$("#clipurl input").css("font-weight","bold");
		setTimeout('$("#clipurl input").attr("value","'+value+'");$("#clipurl input").css("color","#000000");',2000);
	});

}
function copyepisode(value){
	var clipcopy2 = new ZeroClipboard.Client();
	clipcopy2.setText(value);
	clipcopy2.glue('episodecopy');
	clipcopy2.addEventListener('complete', function(client, value) {
		//alert("Copied text to clipboard:\n" + value);
		$("#episodeurl input").attr("value","URL added to clipboard");
		$("#episodeurl input").css("color","#ff0000");
		//$("#episodeurl input").css("font-weight","bold");
		setTimeout('$("#episodeurl input").attr("value","'+value+'");$("#episodeurl input").css("color","#000000");',2000);
	});

}
function copyembed(value){
	var clipcopy3 = new ZeroClipboard.Client();
	clipcopy3.setText(value);
	clipcopy3.glue('embedcopy');
	clipcopy3.addEventListener('complete', function(client, value) {
		//alert("Copied text to clipboard:\n" + value);
		$("#videoembed textarea").html("Embed Code Copied To Clipboard");
		$("#videoembed textarea").css("color","#ff0000");
		//$("#videoembed textarea").css("font-weight","bold");
		setTimeout('$("#videoembed textarea").html("'+addslashes(value.replace(/</g,"&lt;"))+'");$("#videoembed textarea").css("color","#000000");',2000);
	});

}
function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}
//called whenever user login state changes
function pageSessionUpdate(){
	if (getCookie("mml")==null || getCookie("mml")==""){
		$("#VideoComments #CommentPost").css("height","10px");
	} else {
		$("#VideoComments #CommentPost").css("height","248px");
	}
	//auto like mm heart button after login if needed
	if(autolike == 1){
		doLike();
	}
}
function closeVideoComments(speed){
	if (speed==null){ speed="slow"}
	$("#videocommentsbutton").css("background-position","0px -29px");
	$("#videocommentsbutton").css("height","20px");
	$("#videocommentsbutton").attr("class","off");
	$("#VideoComments").hide(speed);	
}
function closeVideoShare(speed){
	if (speed==null){ speed="slow"}
	$("#sharevideobutton").attr("class","off");
	$("#VideoShareLinks").hide(speed);
	$("#sharevideobutton").css("background-position","0 -29px");
	$("#sharevideobutton").css("height","20px");
}
//much heart button function
function likeThis(){
	if (getCookie("mml")!=null && getCookie("mml")!="")
	{
		doLike();
	}
	else
	{
		openwindow2();
		tWin2(); 
		autolike = 1;
		return false;
	}
}

//much heart button function
function doLike(){
	if (getCookie("mml")!=null && getCookie("mml")!="")
	{
		//user is logged in, enter contest...
		var usersession=getCookie("mml").substring(getCookie("mml").indexOf('|')+1).split("|")[0];
		var userid=getCookie("mml").substring(getCookie("mml").indexOf('|')+1).split("|")[1];
		
		$.getJSON("http://webservices.muchmusic.com/connect/elastica.php?jsoncallback=?", 
		{ act: "like", userid: userid, unittype: unit_type, unitid: unit_id, brand: 2, like: like, session: usersession } ,
			function(data){
				if (data.success == 0)
				{
					//unsuccessful, user must have already liked this video...
					$("#heart").css("background-position", "0 -24px");
					$("#heart").attr("title","un-heart this");
					$("#heart").unbind('mouseenter mouseleave');
					getLikeCount();
				}
				else 
				{
					//success
					if (like == 1){
						like = 0;
						$("#heart").css("background-position", "0 -24px");
						$("#heart").attr("title","un-heart this");
						$("#heart").unbind('mouseenter mouseleave');
						getLikeCount();
					}else{
						like = 1;
						$("#heart").css("background-position", "0 0");
						$("#heart").attr("title","Heart this!");
						$("#heart").hover(function(){
						$("#heart").css("background-position", "0 -24px");
					},function(){
						$("#heart").css("background-position", "0 0");
					});
						getLikeCount();
					}
				}
			}
		);
	}
}
//much heart button function
function getLikeCount(){
	$.getJSON("http://webservices.muchmusic.com/connect/elastica.php?jsoncallback=?", 
		{ act: "getlikescount",  unittype: unit_type, unitid: unit_id, brand: 2 } ,
		function(data){
			if (data.success == 0)
			{
				$("#likeCount").html("Error");
				//unsuccessful
			}
			else 
			{
				$("#likeCount").html(data.count);
				//success
			}
		}
	);
}

function hasUserLiked(){
	//userid=108&session=xyz
	if (getCookie("mml")!=null && getCookie("mml")!="")
	{
		//user is logged in...
		var usersession=getCookie("mml").substring(getCookie("mml").indexOf('|')+1).split("|")[0];
		var userid=getCookie("mml").substring(getCookie("mml").indexOf('|')+1).split("|")[1];
		
		$.getJSON("http://webservices.muchmusic.com/connect/elastica.php?jsoncallback=?", 
			{ act: "hasuserlikedthis",  unittype: unit_type, unitid: unit_id, brand: 2, userid: userid, session: usersession } ,
			function(data){
				if(data.success && data.msg){
					//user has liked this
					$("#heart").css("background-position", "0 -24px");
					$("#heart").attr("title","un-heart this");
					$("#heart").unbind('mouseenter mouseleave');
					like = 0;
					getLikeCount();
				} else {
					$("#heart").attr("title","Heart this!");
					$("#heart").hover(function(){
						$("#heart").css("background-position", "0 -24px");
					},function(){
						$("#heart").css("background-position", "0 0");
					});	
				}
			}
		);
	}		
}
$(document).ready(function(){
	//google +1 script
	(function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
	})();
	
	//Fix ie7 copy button bug
	if(navigator.userAgent.indexOf("MSIE 7")!="-1"){
		$("#VideoShareLinks").show();
		closeVideoShare();
	}
	
	$("#clipurl input").focus(function(){
		this.select();
	});
	$("#clipurl input").click(function(){
		this.select();
	});
	$("#episodeurl input").focus(function(){
		this.select();
	});
	$("#episodeurl input").click(function(){
		this.select();
	});
	$("#videoembed textarea").focus(function(){
		this.select();
	});
	$("#videoembed textarea").click(function(){
		this.select();
	});
	$("#sharevideobutton").click(function(){
		var sharebuttonstatus=$("#sharevideobutton").attr("class");
		var commentstatus=$("#videocommentsbutton").attr("class");
		if (commentstatus=="on"){
			closeVideoComments("fast");
		}
		if (sharebuttonstatus=="off"){
			$("#VideoShareLinks").show();
			$("#sharevideobutton").attr("class","on");
			$("#sharevideobutton").css("background-position","0 0");
			$("#sharevideobutton").css("height","29px");
			copyclip($("#clipurl input").attr("value"));
			if (pid==""){
				$("#episodeurl").hide();
			}
			if (pid!=""){
				$("#episodeurl").show();
				$.get("/feeds/EpisodeFeed.aspx?video_package_id="+pid, function(data){
					var eptitle=sluggify($(data).find('headline').text());
					$("#episodeurl input").attr("value",episodeurl+eptitle);
					copyepisode($("#episodeurl input").attr("value"));
				}, "xml");
			}
			$.getJSON("http://webservices.muchmusic.com/allowlist/doAllow.php?callback=?&mode=chk&orgid=299&vid="+cid+"&rettype=jsonp&isca=1", function(data){
					if(data.success==1){
						$("#videoembed").show();
						$("#videoembed textarea").html("&lt;script src=\"http://www.muchmusic.com/flashmodules/scripts/embedplayer.js?vid="+cid+"\" type=\"text/javascript\" &gt;&lt;/script&gt;");
						copyembed($("#videoembed textarea").html().replace(/&lt;/g,"<").replace(/&gt;/g,">"));
					} else {
						$("#videoembed").hide();
					}
			});
		} else{
			closeVideoShare();	
		}
		return false;
	});
	$("#CloseShareLinks").click(function(){

		closeVideoShare();
		return false;			
	});
	
	//VIDEO COMMENTING START
	$("#videocommentsbutton").click(function(){
		var commentstatus=$("#videocommentsbutton").attr("class");
		var sharebuttonstatus=$("#sharevideobutton").attr("class");
		if (sharebuttonstatus=="on"){
			closeVideoShare("fast");
		}
		if (cid!=null&&commentstatus=="off"){
			$("#videocommentsbutton").attr("class","on");
			$("#videocommentsbutton").css("background-position","0px 0px");
			$("#videocommentsbutton").css("height","29px");
			$("#VideoComments").show();
			$("#VideoCommentsLoading").show();
			//ajax load comments
			$("#LoadVideoComments").load("/includes/home30/videoplayer/comments.aspx?u_type="+unit_type+"&u_id="+unit_id,function(){
				if (getCookie("mml")==null || getCookie("mml")==""){
					$("#VideoComments #CommentPost").css("height","35px");
					$(".CommentReply").each(function(){
						$(this).replaceWith("<a href=\""+$(this).attr("href")+"\" class=\"CommentReply\" onclick=\"openwindow2();tWin2(); return false\">LOGIN TO REPLY</a>");
					});
				} else {
					$("#VideoComments #CommentPost").css("height","248px");
					$(".CommentReply").each(function(){
						$(this).replaceWith("<a href=\""+$(this).attr("href")+"\" class=\"CommentReply\" onclick=\"CommentReply("+$(this).attr("href").substring($(this).attr("href").indexOf("#reply")).substring(6)+");return false\">REPLY</a>");
					});
				}
				$("#VideoCommentsLoading").hide();
				if(offset + commentPageSize < numcomments){
					$("#comment-navigation").html("<a href=\"#\" onclick=\"moreComments(); return false;\"> MORE COMMENTS <img src=\"http://www.muchmusic.com/mmconnect/images/down_arrow_small.gif\" /></a>");
				}
			});
		}else if (commentstatus=="on"){
			closeVideoComments();
		}
		return false;
	});
	$("#CloseVideoComments").click(function(){
		closeVideoComments();
		return false;
	});
	
	//Fix firefox scrolling double click bug on share button
	if(navigator.userAgent.indexOf("Firefox")!="-1"){
		var scrollon=0;
		$(window).scroll(function () { 
			if (scrollon==0){
			$("#clipurl").css("background","transparent");
			$("#episodeurl").css("background","transparent");
			$("#videoembedurl").css("background","transparent");
				scrollon=1;
			} else{
			$("#clipurl").css("background","#f2f2f2");
			$("#episodeurl").css("background","#f2f2f2");
			$("#videoembedurl").css("background","#f2f2f2");
				scrollon=0;
			}
		});
	}

	//VIDEO COMMENTING END
});
