var uShow = {};

/* Maximum number of film strip frames to show */
uShow.fsMaxf = 5;

/* Misc add and remove highL class on mouse overs and outs */
uShow.highLOn    = function(self) {$(self).addClass("highL");};
uShow.highLOff = function(self) {$(self).removeClass("highL");};

uShow.highP    = function() { $(this).addClass("highP");    };
uShow.highPOff = function() { $(this).removeClass("highP"); };

uShow.highLFrameOn  = function(self) {
	var frame_id = $(self).attr("frame_id_v") || $(self).attr("frame_id");
	$("[frame_id="+frame_id+"]").addClass("highL"); 
};

uShow.highLFrameOff = function(self) { 
	var frame_id = $(self).attr("frame_id_v") || $(self).attr("frame_id");
	$("[frame_id="+frame_id+"]").removeClass("highL"); 
};

uShow.highLFrameVOn  = function(self) {
	var frame_id = $(self).attr("frame_id_v") || $(self).attr("frame_id");
	$("[frame_id_v="+frame_id+"]").addClass("highL"); 
};

uShow.highLFrameVOff = function(self) { 
	var frame_id = $(self).attr("frame_id_v") || $(self).attr("frame_id");
	$("[frame_id_v="+frame_id+"]").removeClass("highL"); 
};

uShow.setLiveHoverClick = function(select, mouseover, mouseout, click) {
	var target = $(select);
	if (mouseover) target.live('mouseover', mouseover);
	if (mouseout) target.live('mouseout', mouseout);
	if (click) target.live('click', click);
}


/******
* Video Detail Edit
*******/
uShow.videoedit = {};
uShow.videoedit.setListen = function(link) {
	$(link+" .inputsubmit").click(function() {
		var form = $(link + " form");
		var url = form.attr("action");
		$.post(url, form.serialize(), function(data, textStatus) {
			uShow.clearErrors(link);
			if (data.is_ok) {
				var video = data.video;
				jQuery.each(data.value, function(key,val){
					$('#display_'+key+"_"+video).html((val=="") ? "---" : val);
					if (key == "title") $(".video_title_"+video).html(val);
					if (key == "desc_full") $("#video_desc_full_"+video).html(val);
					if (key == "category") $("#video_category_"+video).html(val);
				});
				$(link + " .settings_toggle").trigger('click');
			}
			if (data.message) uShow.showDialogOK("Confirmed", data.message);
			if (data.error) uShow.setErrors(link, data.error);
		}, "json");
	});
}

uShow.videoedit.init = function() {	
	$(".settings_section").each(function(){
		uShow.setToggleHand('#' + this.id);
		uShow.videoedit.setListen('#' + this.id);
	});
};


/******
* NOTIFICATIONS 
*******/

uShow.notifications = {};
uShow.notifications.decrement = function(){
	$('.num_notifications').each(function(){
		$(this).text( parseInt($(this).text()) - 1 );
		});
}

uShow.setLive = function() {
	
	$('div.notify-head').live('click', uShow.goToHref);
	// IE fix for rounded corners
	$('a.cw50, a.top-story-thumbnail').live('click', uShow.goToHref);
	
	/**
	* Set Comment links on story listings to slidedown the hidden comment form.
	*/
	$('.comments-link a').live('click', function(){
		var target = $(this),
		form = $(target.attr('form')),
		is_vis = target.attr('vis');
		if (is_vis != 0) {
			form.fadeOut('fast', function() {
				target.attr('vis', 0);
			});
		}
		else {
			form.fadeIn('fast', function(){
				$(this).find('form textarea').focus();
				target.attr('vis', 1);
			});
		}
		return false;
	});	
	
	
	/**
	* Set delete links in notifications to AJAX
	*/
	$('a.hide_notif').live('click', function(){
		$.post($(this).attr('href'));
		uShow.notifications.decrement()
		$(this).parent().slideUp('slow');
		return false;
	});

	/**
	* Search query clear 
	*/
	$("#query").live('click', function() {
		$(this).val("");
	});


	/**
	 * Pagination
	 */

	$(".ui-tabs-panel .paginator a").live('click', function() {
		var container = $(this).closest(".ui-tabs-panel");
		url = $(this).attr("href");
		$.get(url, null, function(data, textStatus) {
			container.html(data);
			uShow.setScroll();
			uShow.setStoryCount();
		});
		return false;
	});

	/**
	 * Show more
	 */

	$(".show-older a").live('click', function() {
		var container = $(this).parent();
		url = $(this).attr("href");
		uShow.showLoading(container, true);
		$.get(url, null, function(data, textStatus) {
			container.replaceWith(data);
			uShow.setScroll();
			uShow.setStoryCount();
			if (pageTracker) pageTracker._trackPageview(url);
		});
		return false;
	});

	/**
	  * Video edit links on feed pages;
	*/
	$(".video-edit").live('click', function() {
		var widget = $(this).closest("li.videolisting").find(".video-edit-widget");
		var text = $(this).text();
		if (text == "Edit") {
			var url = $(this).attr("url");
			uShow.showWaiting(widget);
			widget.slideDown();
			$.get(url, null, function(data, textStatus) {
				widget.html(data);
				widget.find(".settings_section").each(function() {
					uShow.setToggleHand("#"+this.id);
					uShow.videoedit.setListen('#'+this.id);
				});
				if (pageTracker) pageTracker._trackPageview(url);
			});
			$(this).text("Done Editing");
		}
		else {
			$(this).text("Edit");
			widget.fadeOut();
		}
		return false;
	});

	/**
	  * Follow someone;
	*/
	
	$("a.follow").live('click', function(){
		url = $(this).attr("href");
		var anchor = $(this);
		$.get(url,{}, function(data){
			if (data.is_ok) {
				anchor.parent().html("<em>Watching</em>");
				var counter = $("#friends_widget a#a_following span.count");
				var count = parseInt(counter.html());
				count += 1;
				counter.html(count);
				if (pageTracker) pageTracker._trackPageview(url);
			}
		}, "json");
		return false;
	});




	/**
	* Set Highlights on Story items
	*/
	$("a.subject, div.href").live("click", uShow.goToHref);
	//$("a.subject, div.listing-title, div.href").live("click", uShow.goToHref);
	//$("div.listing-title").live("click", uShow.toggleParent);

	uShow.setLiveHoverClick(".storylisting-feed-item", 
							function() { uShow.highLFrameOn(this) }, 
							function() { uShow.highLFrameOff(this) });

	uShow.setLiveHoverClick(".storylisting-item", 
							function() { uShow.highLFrameOn(this) }, 
							function() { uShow.highLFrameOff(this) },
							uShow.tagClick);

	uShow.setLiveHoverClick(".story-summary-item",
							function() { uShow.highLFrameOn(this); 
										 uShow.scrubParent($(".thumbnail-container[frame_id="+$(this).attr("frame_id")+"]")) },
							function() { uShow.highLFrameOff(this) },
							uShow.tagClick);
	
	uShow.setLiveHoverClick(".thumbnail-container",
							function() {uShow.highLFrameOn(this); 
										uShow.scrubParent(this) },
							function() {uShow.highLFrameOff(this) });

	uShow.setLiveHoverClick(".videoplayer .thumbnail-container",
							function() {uShow.highLFrameVOn(this) },
							function() {uShow.highLFrameVOff(this) });
	
	uShow.setLiveHoverClick(".story-videoplayer-item",
							function() {uShow.highLFrameVOn(this) },
							function() {uShow.highLFrameVOff(this) },
							uShow.goToHref);

	/* filmstrip thumb */
	$(".thumbnail-image").live("click", uShow.tagClick);
	
	uShow.setLiveHoverClick("a.big-thumbnail", uShow.startScrub, uShow.stopScrub, uShow.playInline);
	$("a.play1, a.play, a.story-thumbnail").live('click', uShow.playInline);
	$(".inline-hide").live('click', uShow.hideInline);

	// pending thumb generation;
	uShow.setLiveHoverClick("span.vidtagP", uShow.highP, uShow.highPOff);

	// show more / less link;
	$(".comment-show-more").live('click', uShow.expandCM);
	$(".show-more-link").live('click', uShow.expandST);
	$(".collapse").live('click', uShow.toggleAllLI);

	// film strip left and right arrows;
	$(".scroll-prev").live('click', function() { uShow.doScroll($(this), true) });
	$(".scroll-next").live('click', function() { uShow.doScroll($(this), false) });

};

uShow.hideInline = function() {
	var target = $(this), 
	top_parent = target.closest("li.listing");
	container = top_parent.find("div.video-inline"),
	detail = top_parent.find("div.summary-thumbnail");
	top_parent.find(".inline-hide").fadeOut("fast");
	uShow.tagger.animate(top_parent.attr("index"), -1);
	container.fadeOut("fast", function() {
		//detail.fadeIn("fast");
		container.html("");
	});
}

uShow.playInline = function(event) {
	var target = $(this), 
	top_parent = target.closest("li.listing"),
	container = top_parent.find("div.video-inline"),
	detail = top_parent.find("div.summary-thumbnail"),
	com_link= top_parent.find(".comments-link a"),
	url = target.attr("href"),
	ga = target.attr("ga") || url;
	if (event && event.option) url += "?o=" + event.option;
	$.get(url, null, function(data, textStatus) {
		//detail.fadeOut("fast", function() {
			container.html(data);
			container.fadeIn("fast");
			top_parent.find(".inline-hide").show();
			if (com_link.attr('vis') == 1) com_link.trigger('click');
			var top = top_parent.position().top
			if (top_parent) scrollTo(0, top);
			//$("#right_about").css("top", top < 150 ? 150 : top);
			$(".sidead").css("top", top < 230 ? 230 : top);
			if (pageTracker) pageTracker._trackPageview(ga);
		//});
		uShow.setStoryCount();
		uShow.setScroll();
	});
	return false;
}

/* Change location to href attribute value */
uShow.goToHref = function() {
	var href = $(this).attr("href");
	if (href) location.href = href;
};

/* Thumb or story clicked on video player page, tell player to load frame; */
uShow.tagClick = function(event) {
	var target = $(this),
	command = target.attr("flashcmd");
	if (command) {
		try {
			var index = target.closest("li.listing").attr("index") || 0,
			videoPlayer = document['videoPlayer_'+index],
			time = target.attr("time");
			$("div.tag-notice[index="+index+"]").css('visibility','hidden');

			videoPlayer.playStream();
			videoPlayer.jumpToTime(time, command );

			var count_div = target.closest("div[count_url]"),
			count_url = count_div.attr("count_url"),
			video_id = count_div.attr("video_id"),
			tag_id = target.attr("tag_id");
			if (tag_id) {
				$.post(count_url, "video_id="+video_id+"&tag_id="+tag_id, function(data) {}, "json");
			}
		}
		catch(error) { 
			uShow.playInline.call(this);
			//uShow.showDialogOK("Error", error.message) ;
		}
		// <a> tag return false to stop event;
		return false;
	}
	else {
		uShow.playInline.call(this);
		return false;
	}
};

uShow.resetWho = function(index) {
	try {
		var videoPlayer = document['videoPlayer_'+index];
		videoPlayer.reloadWho();
		return 1;
	}
	catch(error) { 
		//uShow.showDialogOK("Error", error.message);
		return 0;
	}
}

uShow.resetVideoWho = function() {
	uShow.resetWho(0);
}

uShow.resetVideoWhoAll = function() {
	$(".inline-videoleft").each(function() {
		var parent = $(this).closest(".listing");
		index = parent.attr("index");
		if (index) {
			if (!uShow.resetWho(index))
			  uShow.playInline.call(this);
		}
	});
}


/* Scrub big thumb from mouse over small thumb or story */
uShow.scrubParent = function(target) {
	$(target).closest("li[numb_frame]").find("a.big-thumbnail")
	  .css('background-position', ($(target).attr('nframe') * -120) + "px 0px");
};

/* Scrub image by shifting background position based on mouse location and number of frames */
uShow.scrub = function(e) {
	var elX = $(this).position().left + $("#ushow").position().left;
	var numb_frame = $(this).closest("li").attr("numb_frame");
	var frame = parseInt(numb_frame * ((e.clientX - elX) / 120));
	if (frame > numb_frame-1) frame = numb_frame-1;
	$(this).css('background-position', frame * -120 + "px 0px");
};

uShow.startScrub = function(e) {
	$(this).mousemove(uShow.scrub);
};

uShow.stopScrub = function(e) {
	$(this).css('background-position', "0 0");
};

/* Scroll filmstrip left or right */
uShow.doScroll = function(target, left) {
	var opposite,
	index = target.closest("li").attr("index") || 0,
	container = $(".filmstrip-container[index="+index+"]"),
	nframes = parseInt(container.attr("numb_frame")),
	nshow = parseInt(container.attr("numb_show")),
	horiz_offset = parseInt(container.attr("hoff")),
	horiz_offset_orig = horiz_offset;
	if (left) {
		horiz_offset -= (nshow - 1);
		if (horiz_offset < 0) horiz_offset = 0;
		opposite = $("#bnx_"+index);
	}
	else {
		horiz_offset += (nshow - 1);
		if (horiz_offset >= nframes - nshow) horiz_offset = nframes - nshow;
		opposite = $("#bpv_"+index);
	}
	container.attr("hoff", horiz_offset);
	container.animate({left: -horiz_offset*86+"px"}, {duration: Math.abs(horiz_offset - horiz_offset_orig) * 150 });
	uShow.setPrevNextState(target, container);
	uShow.setPrevNextState(opposite, container);
}

/* Set filmstrip left / right button state (on, off) */
uShow.setPrevNextState = function(scroll_div, container) {
	var horiz_offset = parseInt(container.attr("hoff")), 
	nframes=parseInt(container.attr("numb_frame")),
	nshow = parseInt(container.attr("numb_show")),
	subdiv = scroll_div.find("div");
	if (scroll_div.hasClass("scroll-prev")) {
		if (horiz_offset > 0) subdiv.addClass("active");
		else subdiv.removeClass("active");
	}
	else {
		if (horiz_offset < nframes - nshow) subdiv.addClass("active");
		else subdiv.removeClass("active");
	}
};

/* Reset filmstrip left / right status on startup */
uShow.setScroll = function() {
	$(".filmstrip-container").each(function() {
		var numb_frame = $(this).children(".thumbnail-container").length;
		$(this).attr("numb_frame", numb_frame);
		$(this).closest("li").attr("numb_frame", numb_frame);
	});
	$(".scroll-prev, .scroll-next").each(function() {
		var index = $(this).closest("li").attr("index") || 0;
		var container = $(".filmstrip-container[index="+index+"]");
		uShow.setPrevNextState($(this), container);
	});
};

uShow.toggleAllLI = function() {
}

uShow.toggleLI = function(target) {
}

uShow.setEC_LI = function(target, mode) {
}

uShow.toggleParent = function() {
}


/* Expand comments and remove link */
uShow.expandCM = function() {
	var target = $(this),
	parent = target.parent(),
	ul_parent = target.closest("ul");
	ul_parent.find("li").fadeIn();
	parent.remove();
}

/* Expand and collapse extra stories in the storySum section */
uShow.expandST = function(event, sel, prox) {
};

uShow.setStoryCount = function() {
};

/* Define the toggle and cancel click operations for a Settings section based on class names */
uShow.setToggleHand = function(link) {
	$(link + " .settings_toggle").text('change')
	  .click(function() { 
		  if ($(this).text() == 'change') {
			  $(link + " .settings_desc").slideToggle("fast", function() {
				  $(link + " .settings_form").slideToggle("fast");
			  });
		  }
		  else {
			  $(link + " .settings_form").slideToggle("fast", function() {
				  $(link + " .settings_desc").slideToggle("fast");
			  });
		  }
		  $(this).text($(this).text() == 'change' ? 'hide' : 'change');
	  });
	$(link + " .inputcancel").click(function() { $(link + " .settings_toggle").trigger('click') });
};

/* Clear error message div and remove field_error class where applied */
uShow.clearErrors = function(link) {
	$(link + " .error_msg").html("");
	$(link + " .field_error").removeClass("field_error");
};

/* Add field_error class to fields returned by Django, append message text to error_msg div */
uShow.setErrors = function(link, errors) {
	for (var f in errors) {
		$("#id_" + f).addClass("field_error");
		$(link + " .error_msg").append("<div>"+errors[f]+"</div>");
	}
	$(".field_error:first").focus();
};

uShow.showDialogOK = function(title, message, callback, args) {
	$("#dialog").dialog("destroy").remove();
	$("#footer").append('<div id="dialog">'+message+'</div>');
	$("#dialog").html(message).dialog({
		title : title || "Alert", 
		buttons : {OK: function() {$(this).dialog('close'); if (typeof callback == "function") callback(args);}}});
};

uShow.deleteDialog = function(div_id, title){
	$(div_id).dialog({
		title : title || "Confirm Delete",
		modal : false, 
		autoOpen : false, 
		overlay : { 
			opacity : 0.5, 
			background : "black" 
		}});
	return $(div_id)
}

$(document).ready(function() {
	uShow.setLive();
	uShow.setScroll();
	uShow.setStoryCount();

	if ($("#system_msg").length) {
		uShow.showDialogOK("Message", $("#system_msg").html());
	}

	if ($("#email_dialog").length) {
		var e = $("#id_email_req"),
		c = $("#email_dialog"),
		err = c.find(".error"),
		url = c.attr("url");
		c.dialog({modal: true, 
				  autoOpen: true,
				  closeOnEscape: false,
				  beforeclose: function(event, ui) {
					  if (event.which) return false;
				  },
				  buttons: {"Get Started": function() { 
					  if (!uShow.email_valid(e.val())) {
						  err.html("Not a valid email").show();
						  return false;
					  }
					  $.post(url, $("#form_email_req").serialize(), function(data) {
						  err.hide();
						  if (data.is_ok) {
							  c.dialog('close');
						  }
						  else {
							  err.html(data.message).show();
						  }
					  }, "json");
				  }}
	  });
	}
});

// email invite



// fbconnect

//window.api_key = '4cc395aa54222cc8a8f9078e887f2817';
// fbjsapi init - FB var 
function ensure_init(callback) {
	if(!window.api_key) {
		window.alert("api_key is not set");
	}
	if(window.is_initialized) {
		callback();
	} else {
		FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
			FB.FBDebug.logLevel = 4;
			FB.FBDebug.isEnabled = true;
			FB.Facebook.init(window.api_key, "/xd_receiver.html");
			
			window.is_initialized = true;
			callback();
		});
	}
}

/*
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}
*/

function facebook_logout(redirect, callback) {
		/* force FB to be logged out */
	FBIntern.Cookie.clear(window.api_key,'/',FB.Facebook.get_baseDomain());
	if (redirect) {
		if (redirect != location.href) location.href = redirect;
		else location.reload();
	}
	else {
		$(".fbname").html("");
		$("#fbconnect_logout").fadeOut('fast', function() {$("#fbconnect_login").fadeIn('fast')});
		if (callback) callback();
		FB.XFBML.Host.parseDomTree();
	}
}

uShow.reload = function() {
	location.reload();
}


function facebook_auth() {
	ensure_init(function() {
		FB.Facebook.get_sessionState().waitUntilReady(function() {

			var session = FB.Facebook.apiClient.get_session();
			var user = session ? session.uid : 0;
			var url = $("#fb_auth").attr("url");

			$.post(url, "fbu="+user, function(data) {
				if (data.is_ok) {
					if (data.redirect) {
						if (data.redirect != location.href) location.href = data.redirect;
						else location.reload();
					}
				}
				else {
					if (data.message) 
						uShow.showDialogOK("Facebook Error", data.message);
				}
			}, "json");
		});
    });
}

// user has clicked fbconnect - callback comes here
function facebook_login(redirect, callback) {
	ensure_init(function() {
		FB.Facebook.get_sessionState().waitUntilReady(function() {

			var session = FB.Facebook.apiClient.get_session();
			var user = session ? session.uid : 0;
			var url = $("#fb_mini_connect").attr("url");

			$.post(url, "fbu="+user, function(data) {
				if (data.is_ok) {

					if (data.message) {
						uShow.showDialogOK("Facebook Connect", data.message, function(refresh) {
							if (redirect != location.href) location.href = redirect;
							else location.reload();
						}, data.refresh)
					}
					else if (redirect) {
						if (redirect != location.href) location.href = redirect;
						else location.reload();
					}
					else {
						$(".fbname").html("<fb:name id=fb_user linked=false uid=loggedinuser useyou=false></fb:name>");
						$("#fbconnect_login").fadeOut('fast', function() {$("#fbconnect_logout").fadeIn('fast')});
						if (callback) callback();
						FB.XFBML.Host.parseDomTree();
					}

				}
			}, "json");
			
		});
    });
}


// if you have element with id of 'flash_message' on page - call this to fade-in, fade-out
function notify(page_element,message,fade_time)
{	
	var e = $(page_element);
	e.html(message);
	e.fadeIn(500);
	setTimeout(function(){
		e.fadeOut(500,
				  function(){
					  e.html("");
					  e.hide()})}, 
	   fade_time);
}

uShow.email_valid = function(addresses) {
	var valid = true;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var emails = addresses.split(",");
	  for (x in emails) {
		  if(reg.test(trim(emails[x])) == false) {
			  valid = false;
		  }
	  }
	return valid;
}

function trim(str){
	var	str = str.replace(/^\s\s*/,''),
	ws = /\s/,
	i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function stripHTML(oldString) {
	var newString = "",
	inTag = false;
	for(var i = 0; i < oldString.length; i++) {
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
			if(oldString.charAt(i+1)=="<") {
			}
			else {
				inTag = false;
				i++;
			}
		}
        if(!inTag) newString += oldString.charAt(i);
	}
	newString = newString.replace(/\s\s*/g, ' ');
	return newString;
}

/**
* Smart Forms, hinting etc.
*/

$.fn.hint = function () {
	return this.each(function () {
		var input = $(this);
		if (input.attr('type')!='text')
			return;
		
    	var form = $(this.form);

		var label = form.find('label[for=' + $(this).attr('id') + ']');
		var text = label.text()
		label.hide();
		
		function remove() {
			if (input.val() === text && input.hasClass('blur')) {
				input.val('').removeClass('blur');
      			}
			}

		input.blur(function () {
			if (this.value === '') {
				input.val(text).addClass('blur');
        	}
		}).focus(remove).blur();
		form.submit(remove);
      	$(window).unload(remove); // handles Firefox autocomplete
    });
};

/** 
* signup form shnizzle
*/
$(document).ready(function(){
	$('form.smartform input').hint();

	$('#signup #id_email').change(function(){
		$('#email_error').remove();
		if (uShow.email_valid($(this).val())){
			$(this).removeClass('error');

			$.post("/signup/test", "email="+$(this).val(), function(data, textStatus) {
				if (!data.is_ok)
				  $("#id_email").addClass('error').after("<p id = 'email_error' class = 'error'>"+data.message+"</p>");
			}, "json");
			
		}
		else{
			$(this).addClass('error').after("<p id = 'email_error' class = 'error'>That doesn't look like a real email...</p>");
		}
	});
	// Check the terms of service checkbox
	$("#signup form").submit(function(){
		if(!$("#signup #id_terms").attr("checked")){
			$("<p>You must agree to the uShow terms of service before joining</p>").dialog();
			return false;
		}
	});	

	$("div.sidead img").show();
});

uShow.FB = {}
uShow.FB.feed = function(t)	{ 
	var feed_data = { "video_title":t.video_title, "images":[{'src':t.video_thumb,'target':'Spherics', 'href':t.story_link}], "video_link":t.video_link,"story_link":t.story_link, "story":t.story_text};
	
	var res = FB.Connect.showFeedDialog(t.template, feed_data, t.fb_id, null, null, FB.RequireConnect.require, function(){
		// display notification
		//notify("#flash_message","successfully published story to your Facebook feed", 1800);
	}); 
}

/*
 show waiting 
*/
uShow.showWaiting = function(el) {
	el.html('<img src="/media/images/waiting.gif" />');
}
uShow.showLoading = function(el, wait) {
	el.html("Loading..." + (wait?'<br><img src="/media/images/waiting.gif">':''));
}

