jQuery(document).ready(function() {

/*-------------------------
	Auto-Complete Search
-------------------------*/
	if (typeof jQuery.fn.suggestiveSearch != 'undefined'){
		jQuery('#tv_search_head').suggestiveSearch({
			searchUrl:'/autosuggest/?q=',
			searchBox:jQuery('#tv_search_head'),
			additionalLinks:true,
			resultLimit:5
		});
	}
	jQuery('#tv_header .SEARCH_FORM').live('focus', function() { jQuery(this).addClass('on'); })
	jQuery('#tv_header .SEARCH_FORM').live('blur', function() { jQuery(this).removeClass('on'); })

/*------------------------------------------------
	Lights Out
	- Removed as part of TVNEXT-7123 & TVNEXT-7124
		just keeping it around in case
		of a revolt.
--------------------------------------------------
	jQuery('.lights_out').click(function(){
		if (jQuery.cookie('lights_out') == 1){	//lights are already out; turn them back on
			jQuery.cookie('lights_out', '', {expires:-1, path:'/', domain:'tv.com'});
			jQuery('body').removeClass('LIGHTS_OUT');

		} else { //turn the lights out
			jQuery.cookie('lights_out', '1', {expires:365*10, path:'/', domain:'tv.com'});
			jQuery('body').addClass('LIGHTS_OUT');
		}
		return false;
	});
*/

/*----------------------------------
	Send options as associative array.
	
	Function: extUrlsTarget: Open External Links in a new url.

	Usage:	
		LinkHelper.init({base:'._bento'});
		LinkHelper.extUrlsTarget(); // Open up links in new window

------------------------------------*/
LinkHelper = {
	defaults : {
		base : 'body', // CSS Selector. Specify the parent element with which to look for links
		whitelist : new Array( // List of domain names which should not be externally linked.
			'tv.com',
			'twitter.com',
			'facebook.com'
		),
	},
	options : {},
	init : function(opts){
		this.options.base = opts.base ? opts.base : this.defaults.base;
		this.options.whitelist = opts.whitelist ? opts.whitelist : this.defaults.whitelist;
	},
	extUrlsTarget : function(){
		var _lh = this;
		$(this.options.base + ' a').each(function(i, e){
			var url = $(e).attr('href');
			var parts = _lh.parseUri(url);
			var isExternal = true;
			jQuery.each(_lh.options.whitelist, function(i, e){
				var re = RegExp(e+'$','i');
				var found = parts.host.search(re);
				if(found != -1){
					isExternal = false;
				}
			});
			if(isExternal){
				$(e).attr('target','tvcom_external');
			}
		});
	},
	parseUri : function(str){
		var	o   = this.parseUri_options,
			m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
			uri = {},
			i   = 14;
	
		while (i--) uri[o.key[i]] = m[i] || "";
	
		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
			if ($1) uri[o.q.name][$1] = $2;
		});
	
		return uri;
	},
	parseUri_options : {
		strictMode: false,
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:   {
			name:   "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
		}
	}
}




/*-----------------------
	User Panel
-----------------------*/
	//figure out how tall the user menu needs to be based on user's window height
	function setMaxHeight(el){
		var faveShowsMaxHeight = jQuery(window).height() / 2;
		jQuery(el).css({'max-height':faveShowsMaxHeight})
	}
	setMaxHeight('#tv_module .fave_shows');

	//when the user resizes their window, adjust the height of the .fave_show menu
	jQuery(window).resize(function(){
		setMaxHeight('#tv_module .fave_shows');
	});

	jQuery('.user_info .menu_icon').click(function(){
		jQuery(this).toggleClass('down');
		jQuery('#tv_module').fadeToggle();

		//if a user clicks outside of the .user_info menu while it's open, close it
		jQuery(window).click(function(e) {
			var menu = jQuery('#tv_module');
			// jQuery 1.6 specific - fade out console when clicked outside of it.
			if (jQuery(e.target).closest(menu).length == 0) {
				jQuery('.user_info .menu_icon').removeClass('down');
				menu.fadeOut();
			}
		});

		//if a user scrolls past the header while the .user_info menu is open, close it
		jQuery(window).bind('scroll', function() {
			var currentScrollPosition = jQuery(window).scrollTop();
			if(currentScrollPosition >= 100){
			jQuery(window).unbind('scroll');
		    jQuery('#tv_module').fadeOut();
		    jQuery('.user_info .menu_icon').removeClass('down');
			}
		});

		return false;
	});

	jQuery('#tv_module .messages, .user_info .messages').click(function(){
		showMyMessages(TV_BASE_URL);
		return false
	});

	jQuery('.user_info .preferences, #tv_module .preferences').click(function(){
		showMyPrefs(GNE_USERNAME,TV_BASE_URL);
	});

	jQuery('.launch_user_preferences').click(function(){
		var ptype = $(this).attr('data-ptype');
		var ptype = typeof ptype != "undefined" ? ptype : "2"
		showMyPrefs(GNE_USERNAME,TV_BASE_URL, ptype);
	});


/*--------------------------------------------------------------
	Show More/Less for Truncated Text
	- you can use the "summary" Smarty modifier
	  to set this up (e.g. /templates/pages/show_summary.tpl)
--------------------------------------------------------------*/
	// show more
	jQuery('.MORE_LESS .show_more').live('click',function(){
		jQuery(this).parents('.MORE_LESS').children('.truncater').hide().next('span').show('fast');
		jQuery(this).parents('.MORE_LESS').append(' <a class="show_less POINTER_LEFT" href="#">Less</a>');
		return false;
	});
	jQuery('.MORE_LESS .show_less').live('click',function(){
		jQuery(this).parents('.MORE_LESS').children('.truncater').css('display','inline').next('span').hide('fast');
		jQuery(this).remove();
		return false;
	});

/*--------------------------------------------------------------
	Show more search results
---------------------------------------------------------------*/
	(function() {
		var start = 1;
		jQuery('a.more_results_link').click(function(event) {
			event.preventDefault();
			jQuery('img.more_results_loader').show();
			var that=this;
			jQuery.get('/ajax_more_results/' + location.search, {
				'start': start = start + 10
			}, function(results) {
				jQuery('img.more_results_loader').hide();
				$(that).before(results);
			});
		})
	})();


/*--------------------------------------------------------------
	ANOTHER Show More/Less for Truncated Text
	- works with the "more()" filter in tv_extras.py
	jQuery('._more_less .show_more').live('click', function(event){
		var context = $(this).closest('._more_less')
		context.find('.ovf').css('display', 'inline');			//show the overflow text
		context.find('.ovfbr').css('display', 'block');			//show br's in the overflow text
		context.find('.show_less').show();						//show the "less" link
		$(this).hide();											//hide the "more" link
		return false;
	});
	jQuery('._more_less .show_less').live('click', function(event){
		var context = $(this).closest('._more_less')
		context.find('.show_more').show();			//show the "more" link
		context.find('.ovf').hide()					//hide the overflow text
		$(this).hide();								//hide the "less" link
		return false;
	});
--------------------------------------------------------------*/


/*--------------------------------------------------------------
	Show/Hide for subsequent divs
	- will show/hide a div, intended for modules
	(e.g. /templates/pieces/module_capsule_reviews.tpl)
--------------------------------------------------------------*/
	jQuery('.SHOW_HIDE .show_more').live('click',function(){
		var thisParent = jQuery(this).parents('.SHOW_HIDE');
		thisParent.next('.HIDE').show();
		jQuery(this).hide();
		thisParent.children('.show_less').show();
		return false;
	});
	jQuery('.SHOW_HIDE .show_less').live('click',function(){
		var thisParent = jQuery(this).parents('.SHOW_HIDE');
		thisParent.next('.HIDE').hide();
		jQuery(this).hide();
		thisParent.children('.show_more').show();
		return false;
	});


/*--------------------------------------------------------------
	More/Less for lists such as related persons/shows on News page
--------------------------------------------------------------*/
	jQuery('li.more_link a').click(function(){
		//alert('foo')
		var thisParent = jQuery(this).parents('ul');
		if (jQuery(this).parent('.more_link').hasClass("more")){
			thisParent.find('.truncated').css('display','block')
			jQuery(this).parent('.more_link').removeClass("more");
			jQuery(this).parent('.more_link').addClass("less");
		} else {
			thisParent.find('.truncated').css('display','none')
			jQuery(this).parent('.more_link').removeClass("less");
			jQuery(this).parent('.more_link').addClass("more");
		}
		return false;
	});

//swaps the default text in and out of the global search box
jQuery('#tv_search_head').swapText();


/*----------------------------------------------------------------
	The function that is called when the TiVo recording_setup
	panel is submitted
	- it just submits the form to the url specified in the
		action of the form, and the back-end handles it from there
----------------------------------------------------------------*/
	jQuery('#tivo_panel .recording_setup').live('submit',function(){
		var actionUrl = jQuery(this).attr('action');
		var formData = jQuery(this).serialize();

		jQuery('.MODAL_BOX').html('<div class="loading"></div>');

		jQuery.get(actionUrl,formData,function(html){
			jQuery('.MODAL_BOX').html(html);
		});

		console.log('submitted!');

		return false;
	});



/*----------------------------------------------------------------
	Assign the class "RESULT_IN_MODAL_BOX" to a link and its
	href will display in the standard modal box.
----------------------------------------------------------------*/
jQuery('a.RESULT_IN_MODAL_BOX').live('click',function(){
		jQuery('body').modalbox({
			contentURL: this.href
		});
		return false;
});

/* Hide the 1px gif dart ads serve even if there is no ad */
if (typeof(TV_REGION) == 'string' && (TV_REGION == 'au' || TV_REGION == 'uk')){
	jQuery('.dart_ad_wrapper img[src*="-grey.gif"]').hide();
}

/*----------------------------------------------------------------
	This is a generic way to track things.  Any element with a data-tracking_category attribute will automatically be tracked.

	category (required)
	The name you supply for the group of objects you want to track.
	These should be high-level categories, like the type of page the action is happening on.
	Example: news, features, shows, etc.

	action (required)
	A string that is uniquely paired with each category,
	and commonly used to define the type of user interaction for the web object.
	Example: feature name, widget name, etc

	label (optional)
	An optional string to provide additional dimensions to the event data.
	These are usually event names.
	Example: twitter_sharing, etc

	value (optional)
	An integer that you can use to provide numerical data about the user event.
	Example: show id, episode id, person id, user id
----------------------------------------------------------------*/
jQuery('[data-tracking_category]').live('mousedown', function(){
	var category = jQuery(this).attr('data-tracking_category');
	var action = jQuery(this).attr('data-tracking_action');
	var label = jQuery(this).attr('data-tracking_label') || '';
	var value = jQuery(this).attr('data-tracking_value') || '';

	/*console.log('category: '+category);
	console.log('action: '+action);
	console.log('label: '+label);
	console.log('value: '+value);*/

	_gaq.push(['_trackEvent', category, action, label, value]);
});




});//Document ready--------------------------------------------------------------------------------

/* Auto-Complete Search */
//Hides the search dropdown
function hideSearchSuggestions(){
	jQuery('#search_suggestions').fadeOut('400');
}
function showSearchSuggestions(){
	jQuery('#search_suggestions').fadeIn('400');
}

function selectAndSubmit(searchTerm){
	jQuery('#tv_search_head').val(searchTerm);
	jQuery('#tv_search_head').parents('form').submit();
}


/* User Menu functions (used to live in sign_in_status.tpl) */
//HideMeDelay - hides an element after a short delay (used by ugglybug to suppress spurious onmouseout events)
var hideMeTimer; //global!
function hideMeDelay(element, callback){
	hideMeTimer = setTimeout("jQuery('"+element+"').fadeOut('200',function(){"+callback+"})",200);
}

//showMyMessages: opens a window displaying user's personal messages
function showMyMessages(base_url){
	if ((typeof base_url) != "string") {var base_url = "http://www.tv.com";}
	jQuery('#tv_module').fadeOut();
	jQuery('.user_info .menu_icon').removeClass('down');
	window.open(base_url +"/pm/inbox.html&bd=nh",
	    "_blank",
	    "width=720,height=580,scrollbars=1,menubar=0,toolbar=0,location=0,status=0,resizable=0"
	).focus();
	return false;
}

//showMyPrefs: opens a window displaying user's preferences settings
// ptype is the panel to show - 2 is default
function showMyPrefs(username, base_url, ptype){
	var ptype = typeof ptype != "undefined" ? ptype : "2"
	if ((typeof username) != "string") {alert("no username provided"); return false;}
	if ((typeof base_url) != "string") {var base_url = "http://www.tv.com";}
	jQuery('#tv_module').fadeOut();
	jQuery('.user_info .menu_icon').removeClass('down');
	window.open(base_url +"/users/" +username+ "/preferences.php?tag=usermenu;preferences&ptype=" +ptype+ "&bd=nh&popup=1",
	    "_blank",
	    "width=720,height=580,scrollbars=1,menubar=0,toolbar=0,location=0,status=0,resizable=0"
	).focus();
	return false;
}

/* this is used for tracking by the relay banner ad */
function redirectToIntendedURL(intendedURL){
	window.location = intendedURL;
}


/* This is where you can extend jQuery... TREAD CAUTIOUSLY! */
jQuery.fn.extend({
	returnFalse:function(){
		return false;
	},
	swapText:function(focusCallback,blurCallback){
		var thisInput = jQuery(this), defaultValue;
		defaultValue = thisInput.attr('defaultValue');

		thisInput.focus(function(){
			var currentValue = thisInput.val();
			jQuery(this).removeClass('search_gray');
			if(currentValue==defaultValue){
				thisInput.val('');
				if(typeof focusCallback == 'function'){
					focusCallback.call(this);
				}
			}
		});

		thisInput.blur(function(){
			var currentValue = thisInput.val();

			if(currentValue==''){
				thisInput.val(defaultValue);
				if(typeof blurCallback == 'function'){
					blurCallback.call(this);
				}
			}
			if(thisInput.val() == defaultValue) {
				thisInput.addClass('search_gray')
			}
		});
	}
});

/*-----------------------------------------------------------------------------------------------------
		Ajax Helpers:
 ------------------------------------------------------------------------------------------------------*/
// ajax_to: performs a simple get ajax call.
// 	url: url to call
// 	to: html element to put new data into
// 	opts: options { callback:yourCallbackFunction, loaderSelect: yourLoaderSelector }
// Example: ajax_to('index.php?ep_id=123&ajax=true', '#main_episode_content', {loaderSelect:'#loaderId'});
function ajax_to(url, to, opts){
	jQuery(opts.loaderSelect).show();
	jQuery(to).empty();
	jQuery.get(url, function(data){
		jQuery(opts.loaderSelect).hide();
		jQuery(to).html(data);
		if(jQuery.isFunction(opts.callback)){
	 		opts.callback.call(this, data);
		}
	});
	return false;
}

/* Display and un-display an ajax busy icon. */
function ajax_busy(event){
	jQuery('#ajax_bizzy_icon').remove();
	//if (jQuery('#ajax_bizzy_icon').length == 0){
		if (typeof event.pageX == "undefined"){
			jQuery('body').append('<img id="ajax_bizzy_icon" style="z-index: 10000; position:absolute;left:50%;top:50%;" src="http://images.tvtome.com/tv/images/icons/ajax_busy.gif"/>')
		} else {
			jQuery('body').append('<img id="ajax_bizzy_icon" style="z-index: 10000; position:absolute;left:' +event.pageX+ 'px;top:' +event.pageY+ 'px;" src="http://images.tvtome.com/tv/images/icons/ajax_busy.gif"/>')
		}
	//}
}

function ajax_done(){
	jQuery('#ajax_bizzy_icon').remove()
}

var Util = {
	// scroll to element if it is not visible on page
	scrollTo : function(jObj, force) {
		if(jObj.length > 0){
			var docViewTop = $(window).scrollTop();
			var docHeight = $(window).height();
			var elemTop = jObj.offset().top - 30;

			if (force || elemTop < docViewTop || elemTop > (docViewTop + docHeight)) {
				jQuery('html,body').animate( {
					scrollTop : elemTop
				}, 500);
			}
		}
	}
};


/*-----------------------------------------------------------------------------------------------------
         Support logging in
 ------------------------------------------------------------------------------------------------------*/

jQuery(function(){
	//...Or just add the "login_required" classname to your link or button:
	jQuery('a.login_required, button.login_required, .login_required a').click(function(){
		auth.loginRequired();
	});

	//...Or to your textarea or text input:
	jQuery('textarea.login_required, .login_required input, input.login_required').focus(function(){
		var thisInputsClass = jQuery(this).attr('class');//will be "1" if it needs to be emptied
        if (auth.loginRequired("you must log in to perform this action")) {
            if (thisInputsClass == 'needs_emptying') {
                //if this is a textarea, empty out the box on focus
                jQuery('.needs_emptying').val('');
            }
        }
	});

});



