var chanidlast = 0;
var chanfocus = 0;
var chanindex = 1;
var howmany = 10;
var winstat = 1;

$(function(){
				$(".accordion").accordion({ header: "h3" });
				$('#mltvtabs').tabs();
				
		$("#vidq").keypress(function(e){
			var testq = $("#vidq").val();
			if (testq != ''){
			   document.onkeypress = myKeyPressed;
			}
		});
});



function getlink(aid){
	$.getJSON("comm.html", { swcomm: 'adlink', aid: aid}, function(json){
            var adurl = json.adurlx;
            //alert(adurl);
            window.location = adurl;
            //window.open(adurl,'_blank');
        });
}

function onBlur() {
	winstat = 0;
};
function onFocus(){
	winstat = 1;
};

if (/*@cc_on!@*/false) { // check for Internet Explorer
	document.onfocusin = onFocus;
	document.onfocusout = onBlur;
} else {
	window.onfocus = onFocus;
	window.onblur = onBlur;
}





function setqbox(resetfocus){
	var vidq = $("#vidq").val();
	if (vidq == '' || vidq == 'SEARCH THIS CHANNEL'){
		if(resetfocus == 1){
			$("#vidq").val('').removeClass("vidqg").addClass("vidq");
		}else if(resetfocus == 2){
			if (vidq == ''){
				$("#vidq").val('SEARCH THIS CHANNEL').removeClass("vidq").addClass("vidqg");
			}
		}else{
			$("#vidq").val('').removeClass("vidq").addClass("vidqg");
		}
	}else{
		$("#vidq").removeClass("vidqg").addClass("vidq");
	}
}

function changeheadlineimage(area,artid){
			    var newsrc = $("#imgsrc_" + artid).html();
			    $("#headlineimg" + area).attr("src", newsrc);
}

function changearticleimage(area,artid){
			    var newsrc = $("#article_" + area + "_imgsrc_" + artid).html();
			    $("#headlineimg" + area).attr("src", newsrc);
}

function logout(){
	$('#commbox').load("comm.html?swcomm=logout", function(){
	setTimeout( "loadpage()", 2*1000 );
	});
}

function checkprefchecks(box){
				if ($(box).attr("checked")) {
				$(box).parents().find("input[type=checkbox]:first").attr("checked","checked");
				$(box).parent().parent().parent().find("input[type=checkbox]").attr("checked","checked");
				} else {
					$(box).parent().parent().parent().find("input[type=checkbox]").removeAttr("checked");
				}
}

function savefav(cid){
	
	if ($("#preffavor" + cid).hasClass('ui-state-default')){
		$("#preffavor" + cid).removeClass('ui-state-default');
		$("#preffavor" + cid).addClass('ui-state-active');
	}else{
		$("#preffavor" + cid).addClass('ui-state-default');
		$("#preffavor" + cid).removeClass('ui-state-active');
	}
		
				$.ajax({
							url: 'comm.html',
							type: 'GET',
							dataType: "text/html",
							data: {swcomm: 'myfavs', cid: cid},
							 success: function(html){
							 	
							 	switchchannels(0);
							 }
				});  
}

function saveprefs(){
				var swcu = '';
				$(".chanchecks").each(function(index){
						
						if ($(this).attr("checked")) {
							//do nothing
						}else{
						swcu = swcu + $(this).val() + ',';
						}
						
				});
				swcu = swcu + '0';
							$.ajax({
							url: 'comm.html',
							type: 'GET',
							dataType: "text/html",
							data: {swcomm: 'saveprefs', swcu: swcu},
							 success: function(html){
							   $('#dialog_prefs').dialog("close"); 
							   switchchannels(0);
							 }
							});  
}

function prefs(){
				$('#dialog_prefs').load("comm.html?swcomm=prefs", function(){
					$('#dialog_prefs').dialog({
						autoOpen: true,
						width: 600,
						height: 500,
						zIndex: 3999,
						buttons: {
							"Save Changes": function() { 
								saveprefs();
							}, 
							"Close": function() { 
								$(this).dialog("close"); 
							} 
						}
					});
				});
}
			
			
function subpage(pagex){
				pagex = escape(pagex);
				$('#subpagewindow').attr("src", "comm.html?swcomm=subpage&pagex=" + pagex);
}
			
			
function react(){
	$('#prefacct').load("comm.html?swcomm=react");
}
			
function login(){
							$("#loginblock2").css("display", "none");
							$("#loginblock1").css("display", "block");
				$('#dialog_login').dialog({
					autoOpen: true,
					width: 300,
					height: 200,
					zIndex: 3999,
					modal: true,
					opacity: 0.4,
					buttons: {
						"Log In": function() { 
							loginnow();
						}, 
						"Cancel": function() { 
							$(this).dialog("close"); 
						} 
					}
				});
}
			
			
function loadpage(){
	window.location = "index.html";
}
			
			
function loginnow(){
				var uname = $("#mltvusername").val();
				var upass = $("#mltvpassword").val();
				$('#loginstat').load("comm.html?swcomm=login&uname=" + uname + "&upass=" + upass, function(){
						var passpf = $("#passpf").val();
						if (passpf == 1){
							$("#loginblock1").css("display", "none");
							$("#loginblock2").css("display", "block");
							setTimeout( "loadpage()", 2*1000 );
						}else{
							$('#loginstat').html("Login Failed");
						}
			});
}
			
			
function resetAddThis(){
				$(".commart .addthis_button").each(function(){
						$(this).attr("onclick", "return addthis_open(this, '', '"+$(this).attr('addthis:url')+"', '"+$(this).attr('addthis:title')+"');");
				});
}

function articlepop(area,artid){
				var getheadline = $("#article_" + area + "_" + artid).attr("headline");
				$("#dialog_arts").attr("title",getheadline);
				$("#dialog_arts").load('comm.html?swcomm=artload&nid=' + artid, function(){
						resetAddThis();
				$('#dialog_arts').dialog({
					autoOpen: true,
					width: 600,
					buttons: {
						"Ok": function() { 
							$(this).dialog("close"); 
						}
					}
				});
				});
}



function commpop(vtitle, vurl, vw, vh, isyt){
				$("#dialog_comm").attr("title",vtitle);
				$("#dialog_comm").load(vurl, function(){
						if (isyt == 1){
							var vw2 = vw - 30;
							var vh2 = vh - 120;
							$("#dialog_comm").html('<object width="' + vw2 + '" height="' + vh2 + '"><param name="movie" value="' + vurl + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + vurl + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + vw2 + '" height="' + vh2 + '"></embed></object>');
						}else{
							
						}
				$('#dialog_comm').dialog({
					autoOpen: true,
					width: vw, 
					height: vh, 
					buttons: {
						"Ok": function() { 
							$(this).dialog("close"); 
						}
					}
				});
				});
}





function navto(url){
	window.location = url;
}

			//swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn)

function loadVideo(playerUrl, autoplay, vidid) {
              swfobject.embedSWF(
              playerUrl + '&rel=0&border=0&fs=1&wmode=transparent&autoplay=' + 
              (autoplay?1:0), 'player', '450', '270', '9.0.0', false, 
              false, {allowfullscreen: 'true', wmode: 'transparent'});
              hovervid(2,vidid);
              
              
              var hasFlash = false;
				try {
				  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
				  if(fo) hasFlash = true;
				}catch(e){
				  if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
				}
				if (hasFlash == false){
					$("#videobox").html('<div style="margin: 20px; width: 200px; padding: 10px; background-color: #ffffff; color: #000000;">This site requires flash. <a href="http://www.adobe.com/products/flashplayer/" target="_blank">Click Here</a> to download.</div>');
				}

}

function hovervid(task,vidid){
    if (task == 2){
        var vdat = $("#tmpvidinfo" + vidid).html();
        if (vdat != null){
        	//$("#smallbtnbar").html('<marquee class="vidmarq" width="288" height="17">' + vdat + '</marquee>&nbsp;&nbsp;&nbsp;&nbsp;');
        }else{
        	//$("#smallbtnbar").html('');
        }
    } else {
        //var vdat = $("#remvidinfo" + vidid).html();
        //$("#smallbtnbar").html('');
    }
    //$("#vidmarq").html(vdat);
}




function channelloadstack(areatofetch){
	
	var vfeed = $("#remvidfeed").val();
	vfeed = vfeed.replace(/&amp;/gi, "&");
	vfeed = vfeed.replace(/&orderby=published/gi, "");
	vfeed = vfeed.replace(/&orderby=rating/gi, "");
	vfeed = vfeed.replace(/&orderby=viewCount/gi, "");
	vfeed = vfeed.replace(/&orderby=relevance/gi, "");
	vfeed = vfeed.replace(/&orderby=commentCount/gi, "");
	vfeed = vfeed.replace(/&orderby=duration/gi, "");
	vfeed = vfeed.replace(/&orderby=title/gi, "");
	
	if (areatofetch == 1){
		if (vfeed.indexOf('playlists') > 0){
			//do nothing
		} else {
			vfeed = vfeed.replace(/callback=\?/gi, "callback=?&orderby=rating");
			channelrefrsh(vfeed,0,0);
		}
	}else if (areatofetch == 2){
		
		vfeed = vfeed.replace(/callback=\?/gi, "callback=?&orderby=published");
		channelrefrsh(vfeed,0,0);
	}else if (areatofetch == 3){
		
		vfeed = vfeed.replace(/callback=\?/gi, "callback=?&orderby=viewCount");
		channelrefrsh(vfeed,0,0);
	}else if (areatofetch == 4){
		if (vfeed.indexOf('playlists') > 0){
			//do nothing
		} else {
			var vidq = $("#vidq").val();
			var vidqlen = vidq.length;
			if (vidqlen <= 3){//>
				vidslidemsg('Your search must be longer than 3 characters.', '#e6e6e6',1);
			}else{
				vidq = vidq.replace(/SEARCH THIS CHANNEL/gi, "");
				if (vfeed.indexOf('q=') > 0){
					var currentq = $("#cflip" + chanidlast).attr("q");
					vfeed = vfeed.replace(/q=.*&restriction/gi, "q=" + currentq + "+%22" + vidq + "%22&restriction");
				}else{
					vfeed = vfeed.replace(/&restriction/gi, "&q=%22" + vidq + "%22&restriction");
				}
				vfeed = vfeed.replace(/&max-results=[0-9]+/gi, "&max-results=" + howmany);
				
				vfeed = vfeed.replace(/callback=\?/gi, "callback=?&orderby=viewCount");
				channelrefrsh(vfeed,0,0);
			}
		}
	}
}


function changelogo(){
	if (winstat == 1){
		var logoarea = getSelectedTabIndex();
		logoarea = logoarea + 1;
		$("#logoslide" + logoarea).load("comm.html?swcomm=nextad&chanidx=" + chanidlast + "&tab=" + logoarea);
	}
		setTimeout( "changelogo()", 10*1000 );
}

function getSelectedTabIndex() { 
    return $('#mltvtabs').tabs('option', 'selected');
}

function selectweather(){
	$.getJSON("comm.html", { swcomm: 'selectweather'});
}


function trackpage(pname){
	$.getJSON("comm.html", { swcomm: 'trackpage', pname: pname});
}

function channelrefrsh(urltofetch, loadfirst, chanidx, desc){
	
	
	
	
	

	
	
	
	var newfeed = 1;
	if (chanidx == 0){
		chanidx = chanidlast;	
	}else{
		chanidlast = 	chanidx;
	}

		$.getJSON("comm.html", { swcomm: 'selectchannels', chanid: chanidx});
	
	var cstat = $("#cflip" + chanidx).attr("s");
	if (loadfirst == 1){
		if ($("#favtopper").length == 1){
			var cstat = $("#channels a:first + a").attr("s");
		} else {
			var cstat = $("#channels a:first").attr("s");
		}
	} else if (loadfirst == -1){
		newfeed = 0;
	}
	
	if (newfeed == 1){
		$('#vidslides').html("");
		chanindex = 1;
	}else{
		$(".tdmore").remove();	
	}
	
	urltofetch = urltofetch.replace(/&start-index=[0-9]?[0-9]?/gi, "");
	urltofetch = urltofetch + '&start-index=' + chanindex;
	
	
	if (cstat == 1){

	
	$("#errorbox").html("");
var vloop = 1;
$("#remvidfeed").val(urltofetch);

if (urltofetch.indexOf('playlists') > 0 || urltofetch.indexOf('favorites') > 0){
	$("#smvbtn1").removeClass('ui-state-default');
	$("#smvbtn1").addClass('ui-state-disabled');
	$("#smvbtn4").removeClass('ui-state-default');
	$("#smvbtn4").addClass('ui-state-disabled');
	$("#vidqbox").css("display","none");
}else{
		$("#smvbtn1").addClass('ui-state-default');
	$("#smvbtn1").removeClass('ui-state-disabled');
	$("#smvbtn4").addClass('ui-state-default');
	$("#smvbtn4").removeClass('ui-state-disabled');
	$("#vidqbox").css("display","block");
}

$.getJSON(urltofetch, function(data) {
		if (newfeed == 1){
			$('#vidslides').html('<table id="vidstrip"><tr id="vidreel"></tr></table><div class="clear"></div>');
		}
    var channame = data.feed.title.$t;
    
    if (data.feed.entry){
    	//do nothing
    }else{
    	var channameurl =  escape(channame);
    	vidslidemsg('There are no video clips that match your search.', '#e6e6e6',1);
    	//$("#errorbox").load("comm.html?swcomm=novids&channame=" + channameurl);

    }

    channame = channame.replace(/Uploads by .* matching query\:/gi, "");
    channame = channame.replace(/YouTube Videos matching query\:/gi, "");
    channame = channame.replace(/"/gi, "");
    channame = "Channel: " + channame;
    
    
    

    
    $.each(data.feed.entry, function(i, item) {
    try {
    var title = item['title']['$t'];
    
    try{
    var ratingx = item['gd$rating']['average'];
    ratingx = ratingx * 16;
    ratingx = '<div class="vidratingsbg"><div class="vidratings" style="width: ' + ratingx + 'px;"></div></div>';
    }
    catch(e){
    ratingx = '<div class="vidratingsbg"></div>';
    //$("#errorbox").append("Error (B): " + e + "<br>");
    }
    if (title.length > 40){
        var extraddd = '...';
    }else{
        var extraddd = '';
    }
    title = title.substr(0, 40);
    title = title + extraddd;
    var video = item['id']['$t'];
    var playerUrl = item['media$group']['media$content'][0]['url'];
    var thumbnailUrl = item['media$group']['media$thumbnail'][0]['url'];
    var recdate = item['updated']['$t'];
    recdate = recdate.substr(0, 10);
    var condata = item['media$group']['media$description']['$t'];
    var vidid = item['id']['$t'];

    
    try{
    var videoid = item['media$group']['yt$videoid']['$t'];
    rExp = /http:\/\/gdata.youtube.com\/feeds\/videos\//gi;
    }
    catch(e){
    	var videoid = item['id']['$t'];
    	rExp = /http:\/\/gdata.youtube.com\/feeds\/videos\//gi;
    }
    
    
    rExp = /http:\/\/gdata.youtube.com\/feeds\/videos\//gi;
    vidid = vidid.replace(rExp, "");
    
    try{
    var viewCount = item['yt$statistics']['viewCount'];
    }
    catch(e){
    var viewCount = 'n/a';
    //$("#errorbox").append("Error (C): " + e + "<br>");
    }
    

    $('#vidreel').append('<td onMouseOver="hovervid(1 , \'' + vidid + '\');" onMouseOut="hovervid(0 , \'' + vidid + '\');" onclick="loadVideo(\'' +  playerUrl +  '\' ,  true ,  \'' +  vidid + '\')">' + 
              '<div class="vidtile"><img src="' +  
              thumbnailUrl +  '" class="vidtileimg"/></div>' + 
              '<div class="vidinfo" id="vidinfo' +  vidid + '"><div class="vidtitle">' +  title +  '</div><div class="viddate">' +  recdate  + '</div></div>' +  
              '<div id="tmpvidinfo' +  vidid + '" style="display: none;">' +  condata +  '</div>' +  
              '<div id="remvidinfo' +  vidid + '" style="display: none;"><div class="vidtitle">' +  title +  '</div><div class="viddate">' +  recdate  + '</div><div class="vidviews">'  +  ratingx +  '</div></div>' + 
              '</td>');
    			//
    
              } 
    catch(e){
    	//$("#errorbox").append("Error (A): " + e + "<br>");
    }
    if (vloop == 1){
    	$("#channelname").html(channame);
    } else if (vloop == howmany){
    	//more button
    $('#vidreel').append('<td class="tdmore" onMouseOver="hovervid(1 , \'' + vidid + '\');" onMouseOut="hovervid(0 , \'' + vidid + '\');" onclick="channelrefrsh(\'' + urltofetch + '\', -1, ' + chanidx + ', \'' + desc + '\');">' + 
              '<div class="vidmore"><img src="images/morebutton2.png" border="0"></div>' +  
              '</td>');

    }
    
    
    var targetvideo = $("#targetvideo").val();
    
    
    if (loadfirst == 1 && vloop == 1 && targetvideo == 0){
        loadVideo(item['media$group']['media$content'][0]['url'], false);
    }else if (targetvideo == videoid){
    	//alert(videoid);
    	loadVideo(item['media$group']['media$content'][0]['url'], false);
    }
    vloop ++;
    chanindex ++;
    
    
    });
    

    
    //remote player check
    var linktouse = 'www.mylocaltv.ca/?c=' + chanidx;
    if ($("#remoteurl").length > 0){
    	linktouse = $("#remoteurl").val();
    }
    
    
    

    	//share button start - desc - chanidx
    	$('#vidshare').html('<div style="float: left; padding: 3px;"><span class="st_facebook_hcount" st_url="http://' + linktouse + '" st_title="MyLocalTV Channel - ' + channame + '"></span><span class="st_twitter_hcount" st_url="http://' + linktouse + '" st_title="MyLocalTV Channel - ' + channame + '"></span><span class="st_sharethis_hcount" st_url="http://' + linktouse + '" st_title="MyLocalTV Channel - ' + channame + '"></span></div><div style="float: left; padding: 3px;"><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2F' + linktouse + '&amp;layout=button_count&amp;show_faces=true&amp;width=100&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:96px; height:21px;" allowTransparency="true"></iframe></div>');
    	if (loadfirst == 0){
    	stButtons.locateElements(); 
    	}
    	//share button end
    
    	
    	



                             
});
	} else {
		vidslidemsg('This channel requires a subscription.<br><br>' + desc, '#e6e6e6',1);
	}
}




function vidslidemsg(msg,clr,msgtype,closestat){
	

	if (msgtype < 11){
		var elmname = "#smsgbox";
		var elmtop1 = "-265px";
		var elmtop2 = "-12px";
		var elmwidth1 = "454px";
		var elmwidth2 = "494px";
		var elmheight = "215px";
		var fadeitems = 1;
		var fadetonum = 0.15;
		var opacofbox = 0.8;
	}else{
		var elmname = "#pref_info";
		var elmtop1 = "10px";
		var elmtop2 = "10px";
		var elmwidth1 = "240px";
		var elmwidth2 = "280px";
		var elmheight = "280px";
		var fadeitems = 0;
		var fadetonum = 0.8;
		var opacofbox = 0.95;
	}
	
	var msgh = $(elmname).css("height");
	
	if (msgh == undefined){
	   var msgh = '0';
	}
	
	msgh = parseFloat(msgh.replace(/px/gi, ""));
	var msghmax = parseFloat(elmheight.replace(/px/gi, ""));
		
		
	if (msgtype == 1 || msgtype == 11){
		$('#vidslides').html('<div class="reelmsg">' + msg + '</div>').css("background-color",clr);
	} else if (msgtype == 2 || msgtype == 12){
		
		
		if (msgh == 1){
			if (fadeitems == 1){
				$('#viditems').fadeTo("slow", fadetonum);
			}
			$(elmname).css("background-color","#dddddd");
			$(elmname).stop().animate({ 
					height: elmheight,
					width: elmwidth1,
					top: elmtop1,
					padding: "20px",
					opacity: opacofbox
			}, 1000 ,function(){
				$(elmname).html(msg);
			});
			
			
		}else if (msgh > 1){
			$(elmname).html(msg);
			if (fadeitems == 1){
				$('#viditems').fadeTo("fast", fadetonum);
			}
			$(elmname).css("background-color","#dddddd");
			$(elmname).stop().animate({ 
					height: elmheight,
					width: elmwidth1,
					top: elmtop1,
					padding: "20px",
					opacity: opacofbox
			}, 1000);

		}

	} else if (msgtype == 3 || msgtype == 13){
		//hide call

		if (closestat == 0 && chanfocus == 0){
			setTimeout("vidslidemsg('',''," + msgtype + ",1)",500);
		}else if (closestat == 1 && msgh == msghmax && chanfocus == 0){
			setTimeout("vidslidemsg('',''," + msgtype + ",2)",500);
		}else if (closestat == 2 && chanfocus == 0){
			
			$(elmname).stop().animate({ 
					height: "1px",
					width: elmwidth2,
					top: elmtop2,
					padding: "0px",
					opacity: opacofbox
			}, 1000 ,function(){
				$(elmname).html("").css("background-color","#ffffff");
				if (fadeitems == 1){
					$('#viditems').fadeTo("slow", 1.0);
				}
			});
			
		}else if (chanfocus == 0){
			
			var checktype = $("#dialog_prefs").css("display");
			if (checktype == "none"){
				setTimeout("vidslidemsg('','',3,1)",500);
			} else {
				setTimeout("vidslidemsg('','',13,1)",500);
			}
		}

		
	}
}

function cfocus(setto){
	chanfocus = setto;
}

function myKeyPressed(e){

e = e || window.event;
var unicode=e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if (unicode == 13){
	var testq = $("#vidq").val();
			if (testq != ''){
				channelloadstack(4);
    		}
}
}



function switchchannels(chanid){
	if (chanid > 0){
	chanidlast = chanid;
	}
	$("#channels").load("comm.html?swcomm=switchchannels&chanid=" + chanid);
}




function searcharticlesnow(tabid){
	var q = $('#searchartbox' + tabid).val();
	q = escape(q);
	$('#artsearchresults' + tabid).remove();
	$('#accordion' + tabid).prepend('<div id="artsearchresults' + tabid + '"><h3><a href="#">Search Results</a></h3><div id="artsearchresultsinner' + tabid + '"><p>Searching...</p></div></div>')
    .accordion('destroy').accordion({ header: "h3" });
    $('#artsearchresultsinner' + tabid).load("comm.html?swcomm=artfind&q=" + q + "&getarea=" + tabid, function(){
    	
    		
    		var qitems = $("#searchitemsreturned" + tabid).val();
    		if (qitems > 50){
    			$('#searchstatus' + tabid).html("Search limited to 50 results. Please refine your search.");
    		} else {
    			$('#searchstatus' + tabid).html("Search produced " + qitems + " result(s).");
    		}


    });
}

function closesearchbox(tabid){
	$('#artsearchresults' + tabid).remove();
	$('#accordion' + tabid).accordion('destroy').accordion({ header: "h3" });
}

function vidnavlr(lr){
	if (lr == 1){
		//move right
		var lrpos = $("#vidslides").scrollLeft();

		lrpos = lrpos + 100;
		$("#vidslides").scrollLeft(lrpos);
	}
	
	if (lr == 0){
		//move right
		var lrpos = $("#vidslides").scrollLeft();

		lrpos = lrpos - 100;
		if (lrpos <= 90){
			lrpos = 0;
		}
		$("#vidslides").scrollLeft(lrpos);
	}
}




