var tweetPoller;
var tweetLoader;

function setHighlights() {									
	for (i=0;i<document.forms.length;i++) {
		//for (j=0;j<document.forms[i].length;j++){
		var arryInput = document.forms[i].getElementsByTagName('input');
		for (j=0;j<arryInput.length;j++) {
			objElement = arryInput[j];
			if(objElement.getAttribute("type").toLowerCase() == "text" || objElement.getAttribute("type").toLowerCase() == "password"){
				addEvent( objElement, 'focus', function(){ cName=this.className; this.className='ffActive'; } );
				addEvent( objElement, 'blur', function(){ this.className=cName; } );
			}
		}
	}
}

function addEvent( obj, type, fn ) {
	if ( obj.attachEvent ) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
		obj.attachEvent( 'on'+type, obj[type+fn] );
	} else
		obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
	if ( obj.detachEvent ) {
		obj.detachEvent( 'on'+type, obj[type+fn] );
		obj[type+fn] = null;
	} else
	obj.removeEventListener( type, fn, false );
}

function addLoadEvent(func) {

  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
	window.onload = func;
  } else {
	window.onload = function() {
	  if (oldonload) {
		oldonload();
	  }
	  func();
	}
  }

}

/*auto included load events*/
//addLoadEvent(setHighlights)

function displayNotice(m,w,n,e) {
	
	if (m.length > 0) {	$('messageList').innerHTML = '<li>' + m + '</li>'; Element.show('messageOut'); Effect.BlindUp('messageOut', {delay: 5.0})}
	if (w.length > 0) {	$('warningList').innerHTML = '<li>' + w + '</li>'; Element.show('warningOut'); Effect.BlindUp('warningOut', {delay: 5.0})}
	if (n.length > 0) {	$('noticeList').innerHTML = '<li>' + n + '</li>'; Element.show('noticeOut'); Effect.BlindUp('noticeOut', {delay: 5.0})}
	if (e.length > 0) {	$('errorList').innerHTML = '<li>' + e + '</li>'; Element.show('errorOut'); Effect.BlindUp('errorOut', {delay: 5.0})}
		
}

function setPrimaryImage(id) {
	$('div.primary').removeClass('primary');
	$('div#image_' + id).addClass('primary').highlight("slow");
}

// ================================
// = inserts <p></p> in MCE field if first text block does not have formatting applied=
// ================================

function mceTagWrap(element_id, html, body) {
 html = trim(html);
 /*check that text starts and ends with tags if not wrap it in <p>s.  
   This only happens for single line text messages*/
  if(html.charAt(0) != "<" || (html.charAt(html.length - 1) != ">" || html.charAt(html.length -2) == "/")) {
	html = "<p>"+html+"</p>";	
  }
 return html;
}
function trim(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}


// ======================================
// = Initialized the team list dropdown =
// ======================================


function dropDownInit() {
	var hovering = false;
	var menuItem = $('.mainNav li.first a')
	menuItem.hover(
		function(){
			hovering = true;
			$('#sportsDropdown').fadeIn('fast');
			$(this).addClass('hovering');
		},
		function(){
			hovering = false;
			setTimeout(function () { 
				if (hovering==false) {	
					$('#sportsDropdown').hide();
					menuItem.removeClass('hovering');					
				} 
			}, 100);
		}
	);
	
	$('#sportsDropdown').hover(
		function(){
			hovering = true
			menuItem.addClass('hovering');
		},
		function(){
			hovering = false;
			setTimeout(function () { 
				if (hovering==false) {	
					$('#sportsDropdown').fadeOut('fast'); 
					menuItem.removeClass('hovering');
				}
			}, 100);
		}
	);
}

// =============================================
// = Trim back latest entries if they overflow =
// =============================================

function trimEntries() {
	var containerHeight = $("div.topRight").height();
	var contentHeight = $("div#topRightContent").height();
	
	// if there are no latest entires, remove the heading and the empty <ul>
	if ($("ul.latestEntries li").length == 0) {
		$("#latestEntriesHeading").remove();
		$("ul.latestEntries").remove();
	}
	
	if (contentHeight > containerHeight) {
		if ($("ul.latestEntries li").length > 0) {
			// remove an li
			$("ul.latestEntries li:last-child").remove();
		}
		else {
			//start removing paragraphs from the entry snippet, starting with the last one
			$("#entrySnippet p:last-child").remove();
		}
		trimEntries();
	}
	else {
		return false;
	}
}

function trimSchedule() {
	var containerHeight = $("div.scheduleItemsWrapper").height();
	var contentHeight = $("div.scheduleItems").height();
	if (contentHeight > containerHeight) {
		// remove a link
		$("div.scheduleItems a:last-child").remove();
		trimSchedule();
	}
	else {
		$("div.scheduleItems a:last-child").css('border-bottom','none')
		return false;
	}
}


// =================================
// = JS for sport filter drop down =
// =================================

function sportFilter(team) {
	
	$("#filterSelected").html(team);
	
	$(".teamSelectDropdown dt a").click(function() {
        $(".teamSelectDropdown dd ul").toggle('fast');
    });
                
    $(".teamSelectDropdown dd ul li a").click(function() {
        var text = $(this).html();
        $(".teamSelectDropdown dt a span").html(text);
        $(".teamSelectDropdown dd ul").hide();
		$('#sport_id').val(getSelectedValue("teamSelect"));
		$('#sport_id_spinner').show(); 
		document.forms[0].submit();
    });
                
    function getSelectedValue(id) {
		return $("#" + id).find("dt a span.value").html();
    }

    $(document).bind('click', function(e) {
        var $clicked = $(e.target);
        if (! $clicked.parents().hasClass("teamSelectDropdown"))
            $(".teamSelectDropdown dd ul").hide('fast');
    });
}

// ================
// = Tweet wall!! =
// ================

function pollTweets() {
	var latest = $("#twitterWall > li:first span.tweetTime").html();
	$.ajax({data:'latest='+latest, dataType:'script', type:'post', url:'/twitter/tweet_poller'});
}

function showTweets() {
	$(".newWallTweet:last").highlight(1000).removeClass("newWallTweet");
}

function twitterPlayPause() {
	var status = $("#twitterPlayPause").attr("rel");
	if (status == "play") { // it is currently paused
		$("#twitterPlayPause").attr("rel","pause");
		pollTweets();
		tweetPoller = setInterval(pollTweets,60000);
		tweetLoader = setInterval(showTweets,3000);
		$("#twitterPlayPause").removeClass('twitterPlay').addClass('twitterPause');
		$("#twitterPlayPause").html("Updating continuously <img src='/images/ajax-loader.gif' height=15 id='twitterLoading'/> ");
	}
	else { // it is currently playing
		$("#twitterPlayPause").attr("rel","play");
		$("#twitterPlayPause").addClass('twitterPlay').removeClass('twitterPause');
		$("#twitterPlayPause").html("Update Live!");
		clearInterval(tweetLoader);
		clearInterval(tweetPoller);
	}
}

// =================
// = Live Blogging =
// =================

var live_blog_active = true;

function pollLiveEntries(){
	
	if (live_blog_active) {
		$('#live_entries_spinner').show();
	
		last_id = $('#live_entries div:last').attr('id');
		last_id = (last_id.substring(0, 11) == 'live_entry_') ? last_id.substring(11) : '0'
	
		jQuery.ajax({
			complete:function(request){$('#live_entries_spinner').hide();}, 
			dataType:'script', 
			type:'post', 
			url:'/blog/live_entries/' + $('#live_entries').attr("rel") + '/' + last_id
		}); 
		
	}
	setTimeout(pollLiveEntries, 5000);
}

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + "; path=/" + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
	// alert("erasing cookie: " + name);
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
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;
        // xd_receiver.php is a relative path here, because The Run Around
        // could be installed in a subdirectory
        // you should prefer an absolute URL (like "/xd_receiver.php") for more accuracy
        FB.Facebook.init(window.api_key, window.xd_receiver_location);

        window.is_initialized = true;
        callback();
      });
  }
}
/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_button_onclick() {

  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
          var user = FB.Facebook.apiClient.get_session() ?
            FB.Facebook.apiClient.get_session().uid :
            null;

          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }

          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          refresh_fb_area();
          // window.location = window.facebook_authenticate_location;
        });
    });
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
  window.location = window.location;
}

function logout() {
  window.location = '/facebook/logout';
}



/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
	// FB.Connect.showFeedDialog(form_bundle_id, template_data);
	FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, null, FB.RequireConnect.require, continuation, "Write Something...");
  });
}

// function facebook_publish_to_stream() {
//   FB.ensureInit(function() {
// 	var actionLinks = [{ "text": "Watch Video", "href": "http://www.myvideosite/videopage.html"}];
// 	var attachment = {'media':[{'type':'image','src':'http://staging.hln.tgfi.net/images/site/dock/butler.png?1251135029','href':'http://www.horizonleague.com/'}]};
// 	FB.Connect.streamPublish('', null, actionLinks, null, "Write Something...", continuation, "this is the text box", false);
//   });	
// }

var continuation = function() { 
	// console.log('here');
};

function facebook_prune_list() {
	
	var i = 0;
	while (i < 50 && $('.fb_message_wrapper').size() > 30) {
		// console.log($('.fb_message_wrapper').size()); 
		$('#fb_messages .fb_message_wrapper:last').remove();
		i++;
	}
			
}

function toggle_dimmer(opacity) {
	if (opacity == null)
		opacity = 0.85;
	if ($('#dimmer_trigger').attr('rel') == 'on') {
		$("#dimmer").attr('src', '/images/light-bulb-off.png');
		$('#dimmer_trigger').addClass("dark");
		$('#dimmer_trigger').attr('rel', 'off');
		$("<div class='dimmer_overlay'></div>").appendTo("div.top");
		$("<div class='dimmer_overlay'></div>").appendTo("div.main");
		$("<div class='dimmer_overlay'></div>").appendTo("div.headerWrapper");
		$("<div class='dimmer_overlay'></div>").appendTo("div.userActions");
		$("<div class='dimmer_overlay'></div>").appendTo("div.footerWrapper");
		$("<div class='dimmer_overlay'></div>").appendTo("div#main_notice");
		$("<div class='dimmer_overlay'></div>").appendTo("div#teamTopLinks");
		$(".dimmer_overlay").css('opacity', opacity).appear("slow");
		$(".video_image_playing").css('z-index',1);
		$(".dimmer_overlay").click(function(){
			toggle_dimmer();
		})
	}
	else {
		$("#dimmer").attr('src', '/images/light-bulb.png');
		$(".video_image_playing").css('z-index',5);
		$('#dimmer_trigger').removeClass("dark");
		$('#dimmer_trigger').attr('rel', 'on');
		$(".dimmer_overlay").fade('slow', function(){
			$(this).remove();
		});		
	}
}

String.prototype.leftPad = function (l, c) { return new Array(l - this.length + 1).join(c || '0') + this; }

function secondsToTime(secs) {
	return (Math.floor(secs/60)).toString().leftPad(2) + ":" + Math.floor(secs % 60).toString().leftPad(2);
}

function featuredSlideshow() {
	var featuredImages;
	var slideshowInterval;
	var slideshowCounter = 0;

	$(document).ready(function(){
		featuredImages = $("#featuredImages img");
	    slideshowInterval = setInterval(slideshowRotate,7000);
	});

	function slideshowRotate() {
		$(featuredImages[slideshowCounter]).fade(400, function(){
			slideshowCounter++;
			if (slideshowCounter == 2)
				slideshowCounter = 0;
			$(featuredImages[slideshowCounter]).fadeIn(500);
		});

	}
	
}

function swapVideo(id, url, poster, autoplay) {
		$('#video-wrapper-library').css({height:"348px"});
	var w = document.createElement("span");
	w.id = id;
	w.style.float = 'right';
	w.style.visibility = 'visible';
	
	var v = document.createElement("video");
	
	original = $('#' + id + ' video');
	
	// get the parent item width if the child is missing.
	if (original.length == 0) {
		v.style.width = '620px';
		v.style.height = '348px';
	}
	else {
		v.style.width = '' + original.width() + 'px';
		v.style.height = '' + original.height() + 'px';
	}
	v.controls = 'true';
	if (!(poster === undefined))
		v.poster = poster;

	var s = document.createElement("source");
	s.src = url;

	v.appendChild(s);		
	w.appendChild(v);
	
	$('#' + id).replaceWith(w);
			
	swapVideoForFlash(id, autoplay);
	
	if (autoplay == true && v.play) {
		v.play();
	}
}

function swapVideoForFlash(id, autoplay) {
	var IsiPhone = navigator.userAgent.indexOf("iPhone") != -1 ;
	 var IsiPod = navigator.userAgent.indexOf("iPod") != -1 ;
	 var IsiPad = navigator.userAgent.indexOf("iPad") != -1 ;

	 var IsiPhoneOS = IsiPhone || IsiPad || IsiPod ;
	var v = $('#' + id + ' video');
 	// if ( !v.load || jQuery.browser.mozilla || jQuery.browser.msie) { // If no or firefox (only ogg theora), use Flash.
  	if (!IsiPhoneOS) {
		// v.stop();
		// v.remove();
		v.attr('src','');
		var poster = v.attr('poster');
    	var params = { allowfullscreen: "true", allowscriptaccess: "always" };
		
		if (autoplay === undefined)
			autoplay = false;			
			
		if (!(poster === undefined) && poster != '')
			var flashvars = { file: '' + $('#' + id + ' video source').attr('src') + '', image: poster, autostart: autoplay, controlbar: 'over' };
		else
			var flashvars = { file: '' + $('#' + id + ' video source').attr('src') + '', autostart: autoplay, controlbar: 'over' };

     	swfobject.embedSWF("/mp4video/player-licensed.swf", id, v.width(), v.height(), "9.0.0", "expressInstall.swf", flashvars, params);

	}
	// }
	
}

var topEntryIndex = 0;
function topEntrySwap(image,index) {
	

	
	if (index == topEntryIndex)
		return;
	else
		topEntryIndex = index;
		
	video_file = $('#he_video_' + index).html();
	if ( video_file != "")
		url = "javascript: topEntryPlay(" + index + ");";
	else
		url = $('#he_url_' + index).html();
	
	$('#topStoryVideo').hide();
	$('#topStoryVideo video').remove();
	$('#topStoryImage').html("<a href='" + url + "'>" + $('#he_photo_' + index).html() + "</a>");
	$('#topStoryImage').show();
	
	$('#topStoryTitle').html($('#he_title_' + index).html()).show();
	$('#topStorySummary').html($('#he_summary_' + index).html()).show();
	$('#topStoryLink').attr('href',$('#he_url_' + index).html());
	$('.topStoryText').show();
}

function topEntryHighlight(image,index) {
	$(".topStoryThumbnails span").each(function(){
		var thumbIndex = $(this).index();
		if (index != thumbIndex) 
			$(this).children('img').fadeTo(100,0.4);
		else 
			$(this).children().fadeTo(250,1);
	});
}

function topEntryPlay(index) {
			
	$('#topStoryImage').hide();
	$('#topStoryVideo').show();
	
	$('.topStoryText').hide();
	
	video_file = $('#he_video_' + index).html();
	poster = $('#he_poster_' + index).html();
	swapVideo('topStoryVideo', video_file, poster, true);										
	
}

// used in the admin tool for page new/edit
function previewPage(form) {
	
	f = document.createElement('form');
	// f.name = 'previewForm';
	f.action = '/this-is-a-test-entry?preview=true'
	f.method = 'post'
	f.target = '_blank';
	
	elems = form.elements;
	for(var i= 0; i < elems.length; i++) {
						
		switch (elems[i].type)
		{				
			case 'text': case 'textarea': case 'hidden':
				el = document.createElement('input');
				el.name = elems[i].name;
				el.type = 'hidden';
				
				if (elems[i].id == 'page_content') {
					i = $('#cke_page_content iframe');
					i.contents().find("body").html();
					el.value = i.contents().find("body").html();
				}
				else {
					el.value = elems[i].value;
				}
				
				f.appendChild(el);
				break;
			// case 'select-one':
			// 	break;
			case 'checkbox':
				el = document.createElement('input');
				el.name = elems[i].name;
				el.type = elems[i].type;
				el.value = elems[i].value;
				el.checked = elems[i].checked;
				el.style.display = 'none';
				f.appendChild(el);					
				break;
			case 'select-one':				
				el = document.createElement('input');
				el.name = elems[i].name;
				el.type = 'hidden';
				el.value = elems[i][elems[i].selectedIndex].value;
				f.appendChild(el);			
			case 'submit': case 'fieldset':	case 'button':
				break;
			default:
				// console.log(elems[i].type);
				// console.log(elems[i]);
		}
	}
	
	document.body.appendChild(f);
	f.submit();
	
}

var featuredImages;
var slideshowInterval;
var slideshowCounter = 0;

function sponsorRotate() {
	featuredImages = $("#sponsorImages a");
	slideshowCounter = Math.floor(Math.random()*featuredImages.length);
	rotateSponsor();
	slideshowInterval = setInterval(rotateSponsor,8000);
}

function rotateSponsor() {
	if ($.browser.msie) {
		$(featuredImages[slideshowCounter]).hide();
		slideshowCounter++;
		if (slideshowCounter == featuredImages.length)
			slideshowCounter = 0;
		$(featuredImages[slideshowCounter]).show();
	}
	else {
		$(featuredImages[slideshowCounter]).fade(400, function(){
			slideshowCounter++;
			if (slideshowCounter == featuredImages.length)
				slideshowCounter = 0;
			$(featuredImages[slideshowCounter]).fadeIn(500);
		});
	}
}

