var showArray;
var $sh_id;
var $ep_id;

function attempt_focus($this){
	setTimeout( function(){ try{
		$($this).focus();
	} catch(e){}
	}, 200);
}

function inArray(needle, haystack) { 
    var length = haystack.length; 
    for(var i = 0; i < length; i++) { 
        if(haystack[i] == needle) return true; 
    } 
    return false; 
}

function connect_fb(){
//alert();
$("<div id='overlayed' class='popuplogin apple_overlay black'><img src='http://www.socialcommentree.com/images/facebook_logo_big.png' title='Connect to facebook'/><p>You must connect with facebook to enable posting to your friends and family</p><p><a href='https://www.facebook.com/dialog/oauth?client_id=126514470740973&redirect_uri=http%3A%2F%2Fwww.socialcommentree.com&state=8d480b7423711561f0446728e09aaa46&scope=email%2Cuser_location%2Cread_stream%2Cpublish_stream'><img src='http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif' style='vertical-align:middle;'/></a></p></div>").appendTo("body");
$("#overlayed").overlay({
	effect: 'apple',
		closeOnClick: false,
		mask: {
			color: '#ebecff',
			loadSpeed: 200,
			opacity: 0.9
			},
	onClose: function(){$("#overlayed").remove();},
	load: true
	});
}
		
function connect_twit(){
$("<div id='overlayed' class='popuplogin apple_overlay black' ><img src='http://www.socialcommentree.com/images/twitter_newbird_blue.png' title='Connect to Twitter'/><p>You must connect with twitter to enable tweeting directly to your followers.</p><p><a href='http://www.socialcommentree.com/twitter_login/'><img src='http://www.socialcommentree.com/images/twitter_darker.png' title='Sign in with Twitter'/></a></p></div>").appendTo("body");
$("#overlayed").overlay({
	effect: 'apple',
		closeOnClick: false,
		mask: {
			color: '#ebecff',
			loadSpeed: 200,
			opacity: 0.9
			},
	onClose: function(){$("#overlayed").remove();},
	load: true
	});
}


$(document).ready(function(){
	$sh_id = $("[name='show_id']").val();
	$ep_id = $("[name='ep_id']").val();
	
	if (!isNaN($("[name='show_id']").val())) showArray = get_show_details($("[name='show_id']").val());
	if ($(".info_box").html()) $(".info_box").show();
	if ($(".error_box").html()) $(".error_box").show();
	
	$("a[href*='http://']:not([href*='"+location.hostname+"'])").live("click", function(){
		var val = $(this).attr("href");
		var cat = $(this).attr("linkType");
		$(this).attr("target","_blank"); 
		$(this).click(function(){trackClick(cat,val);});
		});
	$("img").bind("contextmenu",function(e){return false;});
	
	$(".fader").myImageFader();

	$(".lightbox").colorbox({maxWidth:"90%", maxHeight:"90%"});
	$(".lightbox").each(function(){
		var sty = $(this).find("img").attr("style");
		$(this).find("img").removeAttr("style");
		$(this).wrap("<span class=thumbnail style='"+sty+"' />");
		$(this).after("<span>click to enlarge</span>");
		});

	$("#login").overlay({effect: 'apple', mask: {color: '#ebecff',loadSpeed: 200,opacity: 0.9}, closeOnClick: false});

	$("[rel='#login']").live("click",function(){
		$("#login").overlay().load();
		return false;
		});
		
	$(".click").live("click",function(){
		$href = $(this).attr("href");
		location.href = $href;
		return false;
		});
		
///////////////// FAVOURITE ////////////		
	$(".fav_show").each(function(){
				$(this).live("click",function(){
			$("#login").overlay().load();
			return false;
			});
				});

///////////////// SHARING ////////////		
	$(".fb_im_watching").live("click",function(e){	
		$.post("http://www.socialcommentree.com/fire-ajax.php?table=sharing&type=short_link",{
					href: document.location.href
					},function (data){
					if (!data.err){
						data.arr.message = "is currently watching "+ showArray.name+" on SocialCommenTree";
						post_to_facebook(showArray,data.arr);
					} else {
						alert();
						$("#error").show();
						$("#error").html(data.err);
						}
			},"json");
		return false;
		});

	$(".twit_im_watching").live("click",function(e){	
		$.post("http://www.socialcommentree.com/fire-ajax.php?table=sharing&type=short_link",{
					href: document.location.href
					},function (data){
					if (!data.err){
						data.arr.caption = showArray.name;
						data.arr.description = "is currently watching "+ showArray.name +" on SocialCommenTree " + data.arr.link;
						post_to_twitter(showArray,data.arr);
					} else {
						alert();
						$("#error").show();
						$("#error").html(data.err);
						}
			},"json");
		return false;
		});
		
	$(".tell_friends").each(function(){
		$(this).click(function(){
			$("[rel='#login']").overlay().load();
			});
		});
		


/////////////// USER STUFF
	
	
	$("img.user_img").live({
		click: function(){
			location.href = "http://www.socialcommentree.com/profile/"+$(this).attr("user_id")+"/";
			},
		mouseover: function(){
			var $this = $(this);
			if (!$(this).data("init")){
				$(this).data("init",true);
				var $html;
				$.ajax({
					type: "GET",
					async: false,
					url: $($this).attr("data-url"),
					success: function(j){
						$html = j;
						},
					dataType: "text"
					})
				$(this).attr("title",$html);
				}
			}
		}).tipsy({gravity: $.fn.tipsy.autoNS, live: true, html: true, opacity: 1});
	});

$(window).load(function(){
	var $mouseon = false;
	var $mouseon2 = false;
	var $open;
	$(".dropdown").each(function(){
		$(this).attr("menuIndex",$(this).parent().eq(0).index());
		var $p = $(this).parent().eq(0);
		var $a = $("a:eq(0)",$p);
		$($p).click(function(e){
			if(!$mouseon){
				var current = $('.dropdown:eq(0)',this);
				if (typeof($open) != "undefined" && $open != current.attr("menuIndex")){$("[menuIndex='"+$open+"']").slideToggle(200);}
				current.slideToggle(200);
				$open = current.attr("menuIndex");
				return false;
				}
			});
		$(this).hover(function(){
			$mouseon = true;
		}, function(){
			$mouseon = false;
			});
		$($a).hover(function(){
			$mouseon2 = true;
		}, function(){
			$mouseon2 = false;
			});
		});
	$("body").mouseup(function(){if (!$mouseon && !$mouseon2) {$('.dropdown').slideUp(200); $open = undefined;}});
	});	
	
	
$.fn.myTooltip = function(options){
	var defaults = {
		speed: 200,
		delay: 300,
		left: 0,
		where: $("body")
		};

	var options = $.extend(defaults, options);
	getTip = function() {
		var tTip =
		"<div class='tip'></div>";
		return tTip;
		}
		
	$(defaults.where).prepend(getTip());

	$(this).each(function(){
		var $this = $(this);
		var tip = $('.tip',defaults.where);
		var tipLeft = $(tip).css("left");

		var tTitle = (this.title);
		this.title = "";

		$this.hover(function() {
			tip.html(tTitle);
			setTimer();
			},
			function() {
				stopTimer();
				hideTip();
				}
			);		   
	
		setTimer = function() {
			$this.showTipTimer = setInterval("showTip()", defaults.delay);
			}

		stopTimer = function() {
			clearInterval($this.showTipTimer);
			}

		/* This function stops the timer and creates the
		   fade-in animation                          */
		showTip = function(){
			$(tip).animate({
				left: defaults.left
				},defaults.speed,"easeIn");
			}
		hideTip = function(){
			$(tip).animate({
				left: tipLeft
				},defaults.speed,"easeIn");
			}
		});
	};

function get_show_details($id){
$.ajax({
	type: "POST",
	url: "http://www.socialcommentree.com/fire-ajax.php?table=programme&type=get_show",
	data: ({id: $id}),
	dataType: "json",
	async: false,
	success: function(data){
			if (!data.err){
				a = data.show;
			} else {
				alert(data.err);
				return false;
				}
		}
	});
		
return a;
}


function post_to_facebook(showArray,arr){
FB.ui(
   {
     method: 'feed',
     name: (arr.name ? arr.name : $('meta[name=title]').attr("content")),
     link: arr.link,
     picture: (arr.picture ? arr.picture :  "http://www.socialcommentree.com/images/logo-sqr.jpg"),
     caption: arr.caption,
     description: (arr.description ? arr.description :   $('meta[name=description]').attr("content")),
     message: arr.message
   },
   function(response) {
     if (response && response.post_id) {
       //alert('Post was published.');
		$.post("http://www.socialcommentree.com/fire-ajax.php?table=programme&type=sharing",{
					id: showArray.id,
					ep: $ep_id
					},
				function (data){
					//alert(data);
					if (!data.err){
						
					} else {
						alert(data.err);
						}
				if ($("[name='refresh']").val() == 1){var $to = setInterval(function(){check_new($ep_id);},freq);}
				},"json");   
     } else {
       //alert('Post was not published.');
     }
   }
 );
}

function fb_liked(){
$show_id = $("[name='show_id']").val() ? $("[name='show_id']").val() : 0;
$ep_id = $("[name='ep_id']").val() ? $("[name='ep_id']").val() : 0;
	$.post("http://www.socialcommentree.com/fire-ajax.php?table=sharing&type=fb_liked",{
				id: $show_id,
				ep: $ep_id
				},
			function (data){
				//alert(data);
				if (!data.err){
					
				} else {
					alert(data.err);
					}
			},"json");   
}

function fb_disliked(){
$show_id = $("[name='show_id']").val() ? $("[name='show_id']").val() : 0;
$ep_id = $("[name='ep_id']").val() ? $("[name='ep_id']").val() : 0;
	$.post("http://www.socialcommentree.com/fire-ajax.php?table=sharing&type=fb_disliked",{
				id: $show_id,
				ep: $ep_id
				},
			function (data){
				//alert(data);
				if (!data.err){
					
				} else {
					alert(data.err);
					}
			},"json");   
}

function post_to_twitter(showArray,arr){
	$("body").append("<div id='tbox' style='display: hidden; height: 100%;'></div>");
	$.fn.colorbox({width:"430px", height:"250px", inline:true, href:"#tbox", onClosed: function(){$("#tbox").remove();}, onComplete: function(){
		twttr.anywhere(function (T) {
			T("#tbox").tweetBox({
				label: arr.caption,
				height: 100,
				width: 400,
				defaultContent: arr.description,
				onTweet: function (plain, html){
					$.post("http://www.socialcommentree.com/fire-ajax.php?table=programme&type=sharing",{
								id: showArray.id,
								ep: $ep
								},
							function (data){
								//alert(data);
								if (!data.err){
									
								} else {
									alert(data.err);
									}
							if ($("[name='refresh']").val() == 1){var $to = setInterval(function(){check_new($ep);},freq);}
							},"json");   
					}
				});
			});
		}
	});
}

function comment_sharing_buttons(showArray, e){
	var $t = $(e.target);
	var $p_id = $($t).parents(".judgeshare:eq(0)").attr("data-id");
	if ($t.is("a.facebook")){
		$.post("http://www.socialcommentree.com/fire-ajax.php?table=programme&type=fb_share",{
					id: $p_id,
					href: document.location.href,
					name: showArray.name
					},function (data){
					if (!data.err){
						post_to_facebook(showArray, data.arr);
					} else {
						alert();
						$("#error").show();
						$("#error").html(data.err);
						}
			},"json");
	} else if ($t.is("a.twitter")){
		$.post("http://www.socialcommentree.com/fire-ajax.php?table=programme&type=twitter_share",{
					id: $p_id,
					href: document.location.href,
					name: showArray.name
					},function (data){
					if (!data.err){
						post_to_twitter(showArray,data.arr);
					} else {
						alert();
						$("#error").show();
						$("#error").html(data.err);
						}
			},"json");
		}
}



