var resizeTimer = null;
var navresizeTimer = null;
var adsheight = 50;
var staticNewHeight = 0;
var welcome_width = 0;
var absoluteMode='true';
var TB_HEIGHT = 0;
var TB_WIDTH = 0;
var TB_HEIGHTMaster = 0;
var TB_WIDTHMaster = 0;
var navWidth = 0;
var TB_FULL='';
var TB_WIDTH_FULL='';

$(window).bind('resize', function() {
	if (resizeTimer)
		clearTimeout(resizeTimer);

	myHeightCheck = myHeightCache-$(window).height();
	myWidthCheck = myWidthCache-$(window).width();
	//clearTimeout(navresizeTimer);
	resizeNavigation();
	if(myHeightCheck>50 || myWidthCheck>50 || myHeightCheck<-50 || myWidthCheck<-50)
	{
		resizeTimer = setTimeout(changesize, 50);
	}
	else
	{
		changeSizeSet=true;
		repositionAds();
	}
});

var nextTab='';
var nextObject='';
var textWidth=0;
var navMaxWidth=0;
var newNavWidth=0;
var previousWidth=0;
var isMoreSet=false;
function resizeNavigation(){
	navContainerWidth = $(".navContainer").width();
	navWidth = $(".nav_links ul").width();
	searchContainerWidth = $(".searchContainer").width();
	navMaxWidth=navContainerWidth-searchContainerWidth;
	newNavWidth=navWidth;
	previousWidth=navWidth;
	
	if(navWidth>navMaxWidth){
		/**
		 * Take away
		 */
		var removearray=new Array();
		$($(".linkelement").get().reverse()).each(function(index) {
			
			textWidth=calculateTextWidth($.trim($(this).text()));
			newNavWidth=newNavWidth-textWidth
			
			if(previousWidth>navMaxWidth){
				removearray[index]=$(this);
				previousWidth=newNavWidth;
			}
			else{
				return false;
			}
		});
		var setMoreNumber=removearray.length-1;
		
		

		
		$.each(removearray,function(index){
			if(index==setMoreNumber){
				$('.dd_end').attr("href",$($('a',this)).attr("href"));
			}
			$(this).prev('li').remove();
			$(this).remove();
			$('<li>'+$(this).html()+'</li>').insertBefore(".ddMenu li:first-child");
			
			var str=$(this).html(); 
			var findCurrent=/current/gi;
			if(str.match(findCurrent)=='current'){
				$('.dd_end').addClass('current');
			}
		});
	}
	else
	{
		/**
		 * Add
		 */
		//$(".innerContent").html(navMaxWidth);
		var buildarray=new Array();
		isMoreSet=false;
		$('.ddMenu li').each(function(index) {
			textWidth=calculateTextWidth($.trim($(this).text()));
			newNavWidth=newNavWidth+textWidth
			
			//$(".innerContent").html('Max Nav Width:'+navMaxWidth+' New Nav Width:'+newNavWidth+' This html '+$(this).html()+'<br><br>'+$(".innerContent").html());
			
			if(newNavWidth>navMaxWidth){
				if(!isMoreSet){
					isMoreSet=$(this);
				}
			}
			else{
				buildarray[index]=$(this);
			}
		 });
		
		
		
		var lengthOfObject=$(".linkelement").length-1;
		$(".linkelement").each(function(index) {
			if(lengthOfObject==index){
				nextObject=$(this);
			}
		});
		var setMoreNumber=buildarray.length-1;
		$.each(buildarray.reverse(),function(index){
			if(index==setMoreNumber){
				$('.dd_end').attr("href",$($('a',isMoreSet)).attr("href"));
			}
			$(this).remove();
			$('<li class="sep insertedHide"  style="display:none;"></li><li class="linkelement insertedHide" style="display:none;">'+$(this).html()+'</li>').insertAfter(nextObject);
			var str=$(this).html(); 
			var findCurrent=/current/gi;
			if(str.match(findCurrent)=='current'){
				$('.dd_end').removeClass('current');
			}
		});
		
		$(".insertedHide").slideDown();
	}	
}

function calculateTextWidth(text){
	var multiplier=13;
	if($.browser.mozilla){
		multiplier=13;
	}
	return text.length*multiplier;
}

function facebookLoginIframe() {
	TB_show(
			'Register & Link Facebook',
			'http://www.facebook.com/login.php?return_session=1&nochrome=1&fbconnect=1&extern=2&display=popup&api_key='
					+ fbAppapikey
					+ '&v=1.0&next='
					+ siteUrl
					+ 'login/fbProfile.php?redirect='
					+ redirectUrl
					+ '%3Ffb_login%26fname%3D_opener%26guid%3D0.3034337986799329&cancel_url='
					+ siteUrl
					+ 'login/cancelFacebook.php?redirect='
					+ redirectUrl
					+ '%23fname%3D_opener%26%257B%2522t%2522%253A3%252C%2522h%2522%253A%2522fbCancelLogin%2522%252C%2522sid%2522%253A%25220.422%2522%257D&channel_url='
					+ siteUrl
					+ 'login/fbProfile.php?redirect='
					+ redirectUrl
					+ '&locale=en_US&full=true&keepThis=true&TB_iframe=true&width=468&modal=true&height=200&thickboxOn=true&redirect='
					+ redirectUrl, '', true);
	$("#TB_iframeContent").css("overflow-y", "auto");
}

function facebookLogoutIframe() {
	close_tb();
	facebookIframe = "";
}

function facebookDisappearFrame() {
	$("#loginIframeWrapFacebook").css("display", "none");
	$("#loginIframeFacebook").css("display", "none");
}

function checkSearchForm() {
	var searchForm = document.getElementById("searchForm");
	if (searchForm.value == searchTerm) {
		searchForm.value = '';
		searchForm.focus();
		alert('Please Enter A Search Term');
		return false;
	} else if (!searchForm.value) {
		searchForm.focus();
		alert('Please Enter A Search Term');
		return false;
	} else if (searchForm.value.length <= 2) {
		searchForm.focus();
		alert('Please Enter More Then 2 Characters');
		return false;
	} else {
		document.getElementById('yubmit').click();
		document.search_form.submit;
	}
}

//var SomeVariable = ajaxFunction('ajax.php?something=test');
//alert(SomeVariable);
//
//$("#someId").val(SomeVariable);

function ajaxFunction(urlToGet, content_id, subject_id) {

	if (content_id > '') {
		$("#" + subject_id).html('Loading...');
	}

	var html = $.ajax( {
		url : urlToGet,
		async : false
	}).responseText;

	if (subject_id > '') {
		$("#" + subject_id).html(html);
	}
	return html;
}

function getallajax() {
	var html = $.ajax( {
		url : rootpath + "ajax/index.php",
		data : arguments[0],
		async : false
	}).responseText;
	return html;
};

function confirmation(link, sometext) {
	var answer = confirm(sometext)
	if (answer) {

		window.location = link;
	} else {
		var something = 'nothing';
	}
}

function pmcheck() {
	newmsgs = getallajax('action=pmcheck&update_time=true');

	if (newmsgs == 'logout') {
		this.location = this.location;
	}
	if (newmsgs) {
		$('#inbox_new').removeClass();
		$('#inbox_new').addClass('inbox_new');
	} else {
		$('#inbox_new').removeClass();
		$('#inbox_new').addClass('inbox');
	}
}

function resizeThickbox() {
	var myWidth = 0, myHeight = 0;
	myHeight = $(window).height();
	myWidth = $(window).width();

	TB_HEIGHT = TB_HEIGHTMaster+60;
	TB_WIDTH = TB_WIDTHMaster;
	if(TB_FULL)
	{
		TB_HEIGHT = myHeight - 20;
	}

	if(TB_WIDTH_FULL)
	{
		TB_WIDTH = myWidth - 20;
	}
	var TB_HEIGHT2 = myHeight - 20;
	
	
	if (TB_HEIGHT2 > TB_HEIGHT) {
		TB_HEIGHT2 = TB_HEIGHT;
	}
	if (TB_HEIGHT < 350 || TB_HEIGHT2 < 350) {
		TB_HEIGHT2 = 350;
	}
	var TB_WIDTH2 = myWidth - 20;
	if (TB_WIDTH2 > TB_WIDTH) {
		TB_WIDTH2 = TB_WIDTH;
	}
	if (TB_WIDTH < 600 || TB_WIDTH2 < 600) {
		TB_WIDTH2 = 600;
	}

	TB_WIDTH2 = TB_WIDTH2 - 10;

	$("#TB_window").animate( {
		width : TB_WIDTH2 - 10 + 'px'
	});
	$("#TB_iframeContent").animate( {
		width : TB_WIDTH2 - 68 + 'px',height : TB_HEIGHT2 - 55 + 'px'
	});
	$("#TB_window").animate( {
		marginTop : '-' + parseInt((TB_HEIGHT2 / 2), 10) + 'px',marginLeft : '-' + parseInt((TB_WIDTH2 / 2), 10) + 'px',
		width : TB_WIDTH2 + 'px'
	});
	$("#TB_table").animate( {
		height : TB_HEIGHT2 - 50 + 'px'
	});
}
var changeSizeSet = '';
function changesize() {
	var bodyWidth = $(document).width();
	var padding = 0;
	myHeightCache = $(window).height();
	myWidthCache = $(window).width();
	myHeight = $(window).height();
	myWidth = $(window).width();
	
	/**
	 * If the thickbox is enabled then lets resize it with the browser.
	 */
	if ($("#TB_window").length == 1) {
		resizeThickbox();
	}

	if (typeof (tenTwentyFourMode) == 'string') {
		var padding = -18;
	}

	var innerContentWidth = $(".innerContent").width();
	var topHeaderWidth = $(".topHeader").width();
	var rightSideAdsWidth = (topHeaderWidth - innerContentWidth) - 35;
	var padding = '';
	if(!topHeaderWidth)
	{
		return false;
	}
	if (rightSideAdsWidth < 210) {
		rightSideAdsWidth = 210;
		var padding = -15;
	}

	if (rightSideAdsWidth > 262) {
		rightSideAdsWidth = 262;
	}

	var positionOffset = 15;
	var overUnder = 7.5;

	if ($.browser.mozilla) {
		var positionOffset = 15;
		var overUnder = 11.5;
	}
	if (typeof (tenTwentyFourMode) == 'string' && tenTwentyFourMode > '') {
		positionOffset = 20;
	}

	var pos2 = $(".innerWrapContainer").offset();
	topHeaderHeight = pos2.top - 6;

	var pos = $(".innerContent").offset();

	rightPos = pos.left - positionOffset;

	if (rightPos <= overUnder) {
		rightPos = 0;
	}
	if (typeof (tenTwentyFourMode) == 'string') {
		if (rightPos <= 21.5 & tenTwentyFourMode > '') {
			rightPos = rightPos;
		}
	} else {
		tenTwentyFourMode = '';
	}

	if ($.browser.msie && $.browser.version == '8.0') {
		rightSideAdsWidth = rightSideAdsWidth - 5;
		rightPos = rightPos;
	}
	if ($.browser.msie && $.browser.version == '6.0') {
		if (rightPos <= 18.5) {
			rightPos = (rightPos / 4);
		}
	}


	$(".leftColumnWidth").animate( {
		width : rightSideAdsWidth + "px"
	}, 500);
	if (bodyWidth <= 1003) {
		rightPos = 0;
	}
	changeSizeSet = true;
	

	//$(".innerContent").html(navMaxWidth);
	
	
	var cacheDimensions = getallajax('action=cacheDimentions&rightSideAdsWidth='
			+ rightSideAdsWidth
			+ '&time='
			+ phpTime
			+ '&topHeaderHeight='
			+ topHeaderHeight
			+ '&navMaxWidth='
			+ navMaxWidth
			+ '&myWidth='
			+ myWidth
			+ '&myHeight='
			+ myHeight
			+ '&rightPos='
			+ rightPos
			+ '&tenTwentyFourMode='
			+ tenTwentyFourMode);
	repositionAds();
}

function repositionAds(dontReRun) {
	/**
	 * Reposition if we have the changeSize function ran else wait till the
	 * changesize function is done running.
	 */
	if (changeSizeSet) {
		var myWidth = 0, myHeight = 0;
		var myHeight = 0;
		var myWidth = 0;
		myHeight = $(window).height();
		myWidth = $(window).width();

		absoluteMode = 'true';
		var pos2 = $(".innerWrapContainer").offset();
		topHeaderHeight = pos2.top - 6;
		var scrollTop = $(window).scrollTop();

		rightSideAbsoPos=1;
		if (typeof (tenTwentyFourMode) == 'string' && tenTwentyFourMode > '') {
			rightSideAbsoPos=-1;
		}
		/*
		 * If iPhone else browser
		 */
		if ((navigator.userAgent.match(/iPhone/i))
				|| (navigator.userAgent.match(/iPod/i))||$.browser.chrome||$.browser.safari||$.browser.chrome ||$.browser.msie && $.browser.version == '6.0') {
			
			if (scrollTop >= topHeaderHeight) {
				scrollTop = scrollTop;
			} else {
				scrollTop = topHeaderHeight;
			}
			
			absoluteMode='true';
			$(".sponsors_column").css( {
				position : 'absolute'
			});
			$(".sponsors_column").css( {
				right : rightSideAbsoPos+"px",
				top : scrollTop + "px"
			}, 500);
		} else {
			/*
			 * If the browser's scroll bar isn't past the topHeaderHeight
			 * position keep it at absolute positiong.
			 */
			
			if (scrollTop <= topHeaderHeight||myWidth<1001) {
				absoluteMode = 'true';
				scrollTop = topHeaderHeight;
				
				$(".sponsors_column").css( {
					position : 'absolute'
				});
				$(".sponsors_column").css( {
					right : rightSideAbsoPos+"px"
				}, 500);

			} else {

				absoluteMode = '';
				
				var scrollTop = 0;
				$(".sponsors_column").css( {
					position : 'fixed',
					right : rightPos + "px"
				});
			}

			if (typeof (noads) != 'string') {
				$(".sponsors_column").css( {
					top : scrollTop + "px"
				});
			}
			if (!dontReRun) {
				setTimeout(function() {
					repositionAds('true');
				}, 200);

			}
		}
	}

}


$(window).scroll(function() {
	repositionAds();
});

function rotateTopSponsors() {
	// alert('top sponsors');
	if (typeof (noads) != 'string') {
		$
				.ajax( {
					type : "GET",
					url : rootpath + "ajax/index.php",
					data : 'action=getTopSponsors',
					dataType : "xml",
					success : function(xml) {
						var c = 0
						$(xml)
								.find('sponsor')
								.each(
										function() {
											var banner_url = $(this).find(
													'banner_url').text();
											var banner_name = $(this).find(
													'banner_name').text();
											var banner_image = $(this).find(
													'banner_image').text();
											var banner_id = $(this).find(
													'banner_id').text();
											if (c == 0) {
												/**
												 * Left Sponsor
												 */
												$("#leftTop")
														.html(
																'<a href="'
																		+ rootpath
																		+ 'ads/ads.php?action=click&banner_id='
																		+ banner_id
																		+ '" target="_blank"><img class="leftSponsor" src="'
																		+ imageFtpAddress
																		+ 'ads/images/'
																		+ banner_image
																		+ '"  title="'
																		+ banner_name
																		+ '" alt="'
																		+ banner_name
																		+ '"  border="0" /></a>');
											} else {
												/**
												 * Right Sponsor
												 */
												$("#rightTop")
														.html(
																'<a href="'
																		+ rootpath
																		+ 'ads/ads.php?action=click&banner_id='
																		+ banner_id
																		+ '" target="_blank"><img class="leftSponsor" src="'
																		+ imageFtpAddress
																		+ 'ads/images/'
																		+ banner_image
																		+ '" title="'
																		+ banner_name
																		+ '" alt="'
																		+ banner_name
																		+ '" border="0" /></a>');
											}
											++c;
										});
						if($.browser.chrome&absoluteMode==''||$.browser.safari&absoluteMode=='')
						{
							$(".sponsors_column").css( {position : 'absolute'});
							setTimeout(function(){$(".sponsors_column").css( {position : 'fixed'});},700);
						}
					}
				});
	}
}

function rotateBottomSponsors() {
	// alert('bottom');

	if (typeof (noads) != 'string') {
		$.ajax( {
			type : "GET",
			url : rootpath + "ajax/index.php",
			data : 'action=getBottomSponsors',
			dataType : "xml",
			success : function(xml) {

				$(xml).find('sponsor').each(function() {
					var banner_image = $(this).find('banner_image').text();
					preload_image = new Image(25, 25);
					preload_image.src = imageFtpAddress + 'ads/images/'+banner_image
					
				});

				var c = 0;
				$(xml).find('sponsor').each(function() {
					var banner_url = $(this).find('banner_url').text();
					var banner_name = $(this).find('banner_name').text();
					var banner_image = $(this).find('banner_image').text();
					var banner_id = $(this).find('banner_id').text();
					
					// alert(banner_id);

						//preload_image = new Image(25, 25);
						//preload_image.src = rootpath + 'ads/images/'+banner_image;
						/**
						 * Bottom Sponsors
						 */
						var timer = 300 * c;
						setTimeout(function(){
						$("#bottomAd" + c).html('<a href="' + rootpath
								+ 'ads/ads.php?action=click&banner_id='
								+ banner_id
								+ '" target="_blank"><img src="'
								+ imageFtpAddress + 'ads/images/'
								+ banner_image + '"  title="'
								+ banner_name + '" alt="' + banner_name
								+ '"  border="0" /></a>');
						++c;
						},timer);
					});
				if($.browser.chrome&absoluteMode==''||$.browser.safari&absoluteMode=='')
				{
					$(".sponsors_column").css( {position : 'absolute'});
					setTimeout(function(){$(".sponsors_column").css( {position : 'fixed'});},700);
				}
			}
		});
	}
}

/**
 * @author John Garland
 * @Code References From Remy Sharp
 * @date 2008-03-27
 * @url http://presentelearning.com
 * 
 * See URL for markup examples and screencast
 */
$.fn.toggleFade = function(timer) {
	var distance = 10;
	var time = 500;
	var hideDelay = 500;
	if (timer) {
		var hideDelay = timer;
	}

	var hideDelayTimer = null;

	var beingShown = false;
	var shown = false;
	var info = this;

	this.mouseover(function() {

		if (hideDelayTimer)
			clearTimeout(hideDelayTimer);
		if (beingShown || shown) {
			// don't trigger the animation again
			return;
		} else {
			// reset position of info box
		}
		return false;
	}).mouseout(function() {

		hideDelayTimer = setTimeout(function() {
			var isHidden = false;
			jQuery(info)[isHidden ? "fadeIn" : "fadeOut"]("100");
		}, hideDelay);
		return false;
	});

	return this.each(function() {
		var isHidden = jQuery(this).is(":hidden");
		if (isHidden) {
			var isHidden = jQuery(info).is(":hidden");
			jQuery(info)[isHidden ? "fadeIn" : "fadeOut"]("100");
		}
	});
};

function ShowProgramSponsor() {
	$('#adBannerSponsorWrap').slideDown('slow');
	if (resizeTimer)
		clearTimeout(resizeTimer);
	resizeTimer = setTimeout(function() {
		$('#adBannerSponsorWrap').slideUp('slow');
	}, 20000);
	getallajax('action=shown_program');
}

function ShowCreditAddedMsg() {
	$('#adBannerSponsorWrap').slideDown('slow');
	if (resizeTimer)
		clearTimeout(resizeTimer);
	resizeTimer = setTimeout(function() {
		$('#adBannerSponsorWrap').slideUp('slow');
	}, 20000);
}

function show() {
	$("#master_container").css("display", "block");
	// document.getElementById('loading_div').style.display = 'none';
	if (tb_show) {
		$("#tb_registration_show").css("display", "block");
	}
}

function loadAjaxFunctions()
{
	
	
	
	$('.beautyTip').bt(
			{
			  width: 300, 
			  height: 300,
			  fill: 'white', 
			  cornerRadius: 20, 
			  padding: 20,
			  strokeWidth: 1,
			  cssStyles: {'text-align': 'center'}, 
			  trigger: ['click','mouseout'],
			  hoverIntentOpts: {
				    interval: 1000,
				    timeout: 2000
				  }
			}).css('cursor', 'pointer');
	$('.beautyTipRoll').bt(
			{
			  width: 300,
			  height: 300, 
			  fill: 'white', 
			  cornerRadius: 20, 
			  padding: 20,
			  strokeWidth: 1,
			  cssStyles: {'text-align': 'center'}, 
			  trigger: ['hover','mouseout'],
			  hoverIntentOpts: {
				    interval: 1000,
				    timeout: 2000
				  }
			}).css('cursor', 'pointer');
	$('.beautyTipNoPic').bt('No Thumbnail Available',
			{
			  width: 150, 
			  fill: 'white', 
			  cornerRadius: 20, 
			  padding: 20,
			  strokeWidth: 1,
			  cssStyles: {'text-align': 'center'},
			  trigger: ['click','mouseout']
			}).css('cursor', 'pointer');
	$('.beautyTipNoPicRoll').bt('No Thumbnail Available',
			{
			  width: 150, 
			  fill: 'white', 
			  cornerRadius: 20, 
			  padding: 20,
			  strokeWidth: 1,
			  cssStyles: {'text-align': 'center'},
			  trigger: ['hover','mouseout']
			}).css('cursor', 'pointer');
}

function focusOnSelect(selectTarget)
{
	//this.location='#top';
	$("#mobile").show();
}

$(document).ready(function() {
	if( navigator.userAgent.match(/Android/i) ||
			 navigator.userAgent.match(/webOS/i) ||
			 navigator.userAgent.match(/iPhone/i) ||
			 navigator.userAgent.match(/iPod/i)
			 ){}
	/*
				$('[multiple="multiple"]').each(function () {
					var idofSelect=$(this).attr('id');
					var parentTD=$("#"+idofSelect).parent();
					var offset=parentTD.offset();
					//console.log(offset);
					
					//return false;
					
					//$("#"+idofSelect).hide();
					
					var buildDivSelections='';
					$("#"+idofSelect+" option").each(function (key,value) {
						buildDivSelections=buildDivSelections+'<div style="vertical-align:middle;">'+value.innerHTML+'</div>';
					});
					
					parentTD.append('<div class="tile" onclick="focusOnSelect(\''+idofSelect+'\');" style="border:solid 1px #000000;overflow-y:auto;overflow-x: hidden;width:'+parentTD.width()+'px;height:'+parentTD.height()+'px;">'+buildDivSelections+'</div>');
					$("#"+idofSelect).hide();
					//console.log(idofSelect)​;
					//$('<div class="tile">testing</div>').appendTo();
					//offset.top;
					//offset.left;
					
					//console.log($(this).attr('id'));
					//console.log($(this).parent());
			    });*/
	

	loadAjaxFunctions();
	
	myOldHeightCache=myHeightCache;
	myOldWidthCache=myWidthCache;
	
	myHeightCache = $(window).height();
	myWidthCache = $(window).width();	
	
	if ($.browser.msie && $.browser.version == '6.0') {
		// $(document).pngFix();
	}
	if (facebook_enabled > '' && typeof (enableFacebook) != 'string') {
		loginToFacebook();
	}
	if (user_id == -1) {
		$("#loginIframe").focus();
	}
	
	if (typeof (noads) != 'string' && typeof (ads) == 'string') {
		$(document).everyTime((bottomSponsorTime * 1000), 'label1', function() {
			rotateBottomSponsors();
		}, 1000);

		$(document).everyTime((topSponsorTime * 1000), 'label2', function() {
			rotateTopSponsors();
		}, 1000);
	}

	// Hover and click on editNav links
	
	

	$('td.MyLectures:not(.animatedNav) a').click(function() {
		$(this).parent().unbind('click');
	});
	
	$('td.MyLectures:not(.animatedNav)').hover(function() {
		$(this).removeClass('MyLectures').addClass('MyLecturesOn');
	}, function() {
		$(this).removeClass('MyLecturesOn').addClass('MyLectures');
	}).click(
			function() {
				if ($(this).children("a").attr("class") == 'thickbox') {
					TB_show($(this).children("a").attr("title"), $(this)
							.children("a").attr('href'), '', true);
				} else {
					window.location = $(this).children("a").attr('href');
				}
			});
	
	$('td.editNav:not(.animatedNav) a').click(function() {
		$(this).parent().unbind('click');
	});
	
	$('td.editNav:not(.animatedNav)').hover(function() {
		$(this).removeClass('editNav').addClass('editNavOn');
	}, function() {
		$(this).removeClass('editNavOn').addClass('editNav');
	}).click(
			function() {
				if ($(this).children("a").attr("class") == 'thickbox') {
					TB_show($(this).children("a").attr("title"), $(this)
							.children("a").attr('href'), '', true);
				} else {
					window.location = $(this).children("a").attr('href');
				}
			});

	$('ul li.ddQuickMenu').hover(

	function() {
		$('ul', this).css('display', 'block');
		// $('ul', this).slideDown("fast");

		},

		function() {
			$('ul', this).css('display', 'none');
			// $('ul', this).slideUp("fast");
		});
	$('li.end').hover(

			function() {
				$('ul', this).css('display', 'block');
				$(".end a.dd_end").css(
						{
							'background-image' : 'url(' + rootpath + 'sites/'
									+ site_name
									+ '/images/navigation/'+nav_end_image+')',
							'background-position' : 'right 0px',
							'color' : nav_hover_font_color
						});
			},

			function() {
				$('ul', this).css('display', 'none');
				 if($(".end a.dd_end").attr("class")=='dd_end current')
				 {
					 $(".end a.dd_end").css(
								{
									'color' : nav_hover_font_color
								});
				 }
				 else
				 {
					 $(".end a.dd_end").css(
								{
									'background-image' : 'url(' + rootpath + 'sites/'
											+ site_name
											+ '/images/navigation/'+nav_end_image+')',
									'background-position' : 'right -35px',
									'color' : nav_out_font_color
								});
				 }
				
			});
	
	myHeightCheckOnload = myOldHeightCache-myHeightCache;
	myWidthCheckOnload = myOldWidthCache-myWidthCache;

	if(myHeightCheckOnload>50 || myHeightCheckOnload>50 || myHeightCheckOnload<-50 || myHeightCheckOnload<-50)
	{
		setTimeout(function() {
			changesize();
		}, 2000);	
	}
	else
	{
		changeSizeSet=true;
		repositionAds();
	}
	setTimeout(function() {
		resizeNavigation();
	}, 1000);	
	
	
	if( navigator.userAgent.match(/Android/i) ||
			 navigator.userAgent.match(/webOS/i) ||
			 navigator.userAgent.match(/iPhone/i) ||
			 navigator.userAgent.match(/iPod/i)
			 ){
		
	}else
	{
		tb_init2('a.thickbox2, area.thickbox2, input.thickbox2');// pass
	}
	
	// where
	// to
	// apply
	// thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
	globalonload();
	show();
});

function loginToFacebook() {
	if (typeof FB == 'object') {
		FacebookOnlineStatus = 2;
		
		FB.init({appId: fbAppapikey, status: true, cookie: true,
            xfbml: true});
		FB.getLoginStatus(handleSessionResponse);
	}
}

function handleSessionResponse()
{
	
}

function checkFacebookStatusDelay() {
	setTimeout(checkFacebookStatus, 750);
	var process = getallajax('action=facebookStatus');
	if (process == 'process') {
		processFacebook(user_id);
	}
}

var FacebookOnlineStatus = 2;
var statusResult=2;
function checkFacebookStatus() {
	if (typeof FB == 'object' && FacebookOnlineStatus != null) {
		//var test = FB.Connect.get_status();
		FB.getLoginStatus(function(response) {
			
			
			  if (response.session) {
			    // logged in and connected user, someone you know
				  //alert(response.status);
				  var statusResult=1;
			  } else {
			    // no user session available, someone you dont know
				  //alert(response.status);
				  var statusResult=2;
			  }
			});

	} else {
		setTimeout(function() {
			checkFacebookStatus();
		}, 50);
		return false;
	}

	var orgFacebookOnlineStatus = FacebookOnlineStatus;

	FacebookOnlineStatus = statusResult;

	if (orgFacebookOnlineStatus == 1 && FacebookOnlineStatus == 2
			&& FacebookOnlineStatus != orgFacebookOnlineStatus) {
		var hash = location.hash;

		hash = hash.replace('#_', '');
		if (!hash) {
			hash = 'Facebook';
		}
		if (user_id > -1) {
			top.location = rootpath + 'profile/settings.php?tab=' + hash;
		} else {
			this.location = rootpath + 'registration/?redirect=' + redirectUrl
					+ '&thickboxSwitch=true';
		}
	}
	if (user_id > -1) {
		if (FacebookOnlineStatus == 1 || orgFacebookOnlineStatus == 1
				&& FacebookOnlineStatus == null) {
			$("#facebookConnect").fadeOut();
			setTimeout(function() {
				$("#facebookConnected").fadeIn();
			}, 500);
		} else {
			$("#facebookConnected").fadeOut();
			setTimeout(function() {
				$("#facebookConnect").fadeIn();
			}, 500);
		}
	}
	
	 //alert(FacebookOnlineStatus);
	 //alert(user_id);
}

function refreshForFacebookLogin() {
	top.location = this.location;
}
function logoutFacebook() {
	FB.Connect.logout(function() {
		refreshForFacebookLogin();
	});
}
function processFacebook(user_id) {
	facebookAccount = getallajax('action=facebookCheck&user_id=' + user_id);
	if (facebookAccount > 0) {
		alert('This account is already associated with a facebook account. You will not be able to link your profile.');
		return false;
	} else {
		facebookId = getallajax('action=facebookRegister&user_id=' + user_id);
	
		if (facebookId == 'no') {
			onRegComplete();
		} else {
			onRegComplete();
		}
	}
}

function onRegComplete() {
	top.location = rootpath + 'profile/settings.php?tab=Facebook&final=true';
}

function setPermissions() {
	
	FB.Connect.showPermissionDialog('read_friendlists,email,read_stream,rsvp_event,status_update,offline_access',
			function() {
				setTimeout(onPermissionsDone, 500);
			});
	
	
}

function onPermissionsDone(value) {
	/**
	 * Deprecated untill facebook fixes this. var
	 * notConnectedFriends=checkIfFriendsNotConnected();
	 * 
	 * if(notConnectedFriends>0) { FB.Connect.inviteConnectUsers(); }
	 */
}

/**
 * Ajax function to check if this person has any friends that are on the website
 * but not using facebook connect.
 */
function checkIfFriendsNotConnected() {
	var unconnectedFriendsCount = getallajax('action=unconnectedFBFriends');
	return unconnectedFriendsCount;
}

function facebooksettings() {
	checkFacebookStatus();
	top.location = this.location;
}

function checkFacebookLogin() {
	var loginReply = getallajax('action=checkFacebookLogin');

	if (loginReply == 'login') {
		$.prompt('One Moment Please.<br>Logging In Via Facebook Connect', {
			show : 'slideDown'
		});
		top.location = rootpath + 'index.php';
	} else if (loginReply == 'refresh') {
		$
				.prompt(
						'Your Facebook Session Has Ended.<br>Resetting Facebook Settings',
						{
							show : 'slideDown'
						});

		location.reload(true);
	} else if (loginReply == 'loginReg') {
		top.location = rootpath + 'profile/settings.php?tab=Facebook&final=true';
		return false;
	} else if (loginReply == 'register') {
		top.location = rootpath + 'registration/?thickboxSwitch=true&redirect='
				+ redirectUrl;
		return false;
		// TB_show('Register & Link
		// Facebook','./../registration/index.php?&full=true&keepThis=true&TB_iframe=true&width=768&height=200&thickboxOn=true&redirect='
		// + redirectUrl,'', true);

	}
}

/**
* TIMER FUNCTIONALITY
*/
jQuery.fn.extend( {
	everyTime : function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times)
		})
	},
	oneTime : function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1)
		})
	},
	stopTime : function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn)
		})
	}
});
jQuery.extend( {
	timer : {
		global : [],
		guid : 1,
		dataKey : "jQuery.timer",
		regex : /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers : {
			'ms' : 1,
			'cs' : 10,
			'ds' : 100,
			's' : 1000,
			'das' : 10000,
			'hs' : 100000,
			'ks' : 1000000
		},
		timeParse : function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult
			} else {
				return value
			}
		},
		add : function(element, interval, label, fn, times) {
			var counter = 0;
			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval
			}
			interval = jQuery.timer.timeParse(interval);
			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;
			if (typeof times != 'number' || isNaN(times) || times < 0)
				times = 0;
			times = times || 0;
			var timers = jQuery.data(element, this.dataKey)
					|| jQuery.data(element, this.dataKey, {});
			if (!timers[label])
				timers[label] = {};
			fn.timerID = fn.timerID || this.guid++;
			var handler = function() {
				if ((++counter > times && times !== 0)
						|| fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn)
			};
			handler.timerID = fn.timerID;
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,
						interval);
			this.global.push(element)
		},
		remove : function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			if (timers) {
				if (!label) {
					for (label in timers)
						this.remove(element, label, fn)
				} else if (timers[label]) {
					if (fn) {
						if (fn.timerID) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID]
						}
					} else {
						for ( var fn in timers[label]) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn]
						}
					}
					for (ret in timers[label])
						break;
					if (!ret) {
						ret = null;
						delete timers[label]
					}
				}
				for (ret in timers)
					break;
				if (!ret)
					jQuery.removeData(element, this.dataKey)
			}
		}
	}
});
jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item)
	})
});

function show_missing_info() {
	document.getElementById('missing_info').style.display = 'block';
}
function hide_missing_info() {
	document.getElementById('missing_info').style.display = 'none';
}



function getSession()
{

	setTimeout(function(){var sessionReply = getallajax('checksession=true');


	if(sessionReply>''){
		$(".login_form_msg").slideDown("fast");
			var iframelink = document.getElementById("redirect").value;
			if(!iframelink)
			{
				var iframelink = self.parent.location.href;
				var iframelink = iframelink.split("/");
				var link = '';
				for(i = 0; i < iframelink.length; i++){
					if(add)
					{
						link = link+'/'+iframelink[i];
					}
					if(start && !add)
					{
						link = iframelink[i];
						var add = true;
					}
					var thissplit = iframelink[i];
					if(thissplit == 'trunk' || thissplit.match("presentdiabetes"))
					{
						var start = true;
					}
				}
			}
			else
			{
				var link = iframelink;
			}
					
			var dlink = rootpath+link;
			
			top.location=dlink;
	}},1500);
}



function refreshPage()
{
	window.location=this.location;
}

function slideErrorUp()
{
	$(".login_form_error").slideUp("slow");
}
function slideErrorDown()
{
	$(".login_form_error").slideDown("slow");
}

function checkFacebookLogin()
{

	var loginReply = getallajax('action=checkFacebookLogin');
	
	if(loginReply=='login')
	{
		$(".login_form_msg").slideDown("fast");
		top.location=rootpath + 'index.php';
	}
	if(loginReply=='loginReg')
	{
		$(".login_form_msg").slideDown("fast");
		top.location=rootpath + 'profile/index.php?tab=Facebook';
	}
	else if(loginReply=='register')
	{
		top.location=rootpath + 'registration/?redirect={REDIRECT}&thickboxSwitch=true';
	}
}


function checkLogin()
{
	var username = document.getElementById("emailForm").value;
	var password = document.getElementById("passwordForm").value;

	var id = 'checklogin';
	
	
	if (username == "")
	{
		var result = 'Enter Your Email Address';
		$("#login_error").html(result);
		$(".login_form_msg").slideUp("fast");	
		$(".login_form_error").slideDown("slow");

		var t=setTimeout(slideErrorUp, 5000);
		
		document.getElementById("emailForm").focus();
		//$.prompt(result,{show:'slideDown'});
		//document.getElementById('checklogin').innerHTML = result;
		//document.getElementById('errorHolder').style.display = '';
		return false;
	}
	else if (password == "")
	{
		var result = 'Please enter your password';
		$("#login_error").html(result);
		$(".login_form_msg").slideUp("fast");	
		$(".login_form_error").slideDown("slow");
		document.getElementById("passwordForm").focus()
		var t=setTimeout(slideErrorUp, 5000);
		
		//document.getElementById('checklogin').innerHTML = result;
		//$.prompt(result,{show:'slideDown'});
		//document.getElementById('errorHolder').style.display = '';
		return false;
	}
	
	var d = new Date();
	var t = d.getTime();

	var loginReply = getallajax('action=checklogin&username='+username+'&password='+password+'&time='+t);
		
	return reactToLoginResponse(loginReply);
	return false;
}

function reactToLoginResponse(loginReply)
{
	
	if(loginReply)
	{
		//document.getElementById('errorHolder').style.display = '';
	}
	if(loginReply == 'register')
	{
	var result = 'Please Register/Wrong Email Address';
	$("#login_error").html(result);
	$(".login_form_msg").slideUp("fast");	
	var t=setTimeout(slideErrorDown, 500);
	document.getElementById("passwordForm").focus()
	var t=setTimeout(slideErrorUp, 5000);
	
		//self.parent.document.getElementById('emailForm').value = document.getElementById("emailForm").value;
		//self.parent.TB_show('Login/Reset Your Password', rootpath+'loginreset/?KeepThis=true&TB_iframe=true&height=325&width=590', '', 'on');
		//alert('Your password is not correct. Please try again or use the following to email a password reset link.');
		return false;
	}
	else if(loginReply == 'checkpassword')
		{
		var result = 'Wrong Password';
		$("#login_error").html(result);
		$(".login_form_msg").slideUp("fast");	
		var t=setTimeout(slideErrorDown, 500);
		document.getElementById("passwordForm").focus()
		var t=setTimeout(slideErrorUp, 5000);
		
			//self.parent.document.getElementById('emailForm').value = document.getElementById("emailForm").value;
			//self.parent.TB_show('Login/Reset Your Password', rootpath+'loginreset/?KeepThis=true&TB_iframe=true&height=325&width=590', '', 'on');
			//alert('Your password is not correct. Please try again or use the following to email a password reset link.');
			return false;
		}
		else if(loginReply == 'activated')
		{
			var result = 'Your Account Is Not Active. Please click Forgot Password.';
			$("#login_error").html(result);
			$(".login_form_msg").slideUp("fast");	
			var t=setTimeout(slideErrorDown, 500);
			document.getElementById("passwordForm").focus()
			var t=setTimeout(slideErrorUp, 5000);
			//$.prompt('Your Account Is Not Active. Please click the "Forgot Password" option to resend the activation email and set your password.',{show:'slideDown'});
			return false;
		}
		else if(loginReply == 'cookies')
		{
			var result = 'Please enable cookies in your browser.';
			$("#login_error").html(result);
			$(".login_form_msg").slideUp("fast");	
			var t=setTimeout(slideErrorDown, 500);
			document.getElementById("passwordForm").focus()
			var t=setTimeout(slideErrorUp, 5000);
			//$.prompt('Your Account Is Not Active. Please click the "Forgot Password" option to resend the activation email and set your password.',{show:'slideDown'});
			return false;
		}
		else if(loginReply == 'login')
		{
		
	
			$(".login_form_msg").slideDown("fast");
			var iframelink = document.getElementById("redirect").value;
			
			if(!iframelink)
			{
			
				var iframelink = self.parent.location.href;
				var iframelink = iframelink.split("/");
				var link = '';
				for(i = 0; i < iframelink.length; i++){
					if(add)
					{
						link = link+'/'+iframelink[i];
					}
					if(start && !add)
					{
						link = iframelink[i];
						var add = true;
					}
					var thissplit = iframelink[i];
					if(thissplit == 'trunk' || thissplit.match("presentdiabetes"))
					{
						var start = true;
					}
				}
			}
			else
			{
				var link = iframelink;
			}
					
			var dlink = rootpath+link;
			/*
				John: Leave the following if condition, otherwise your javascript breaks the remember me feature.
			*/
			
			if(document.getElementById("remember_me").checked)
			{
				if(dlink.search(/\?/) < 0)
				{
					dlink = dlink + "?remember_me=" + document.getElementById("remember_me").value;
					
				}
				else
				{
					dlink = dlink + "&remember_me=" + document.getElementById("remember_me").value;
				}
			}
		
			top.location = dlink;
			
			return false;
		}
		else
		{
			var result = 'Your Account Is Not Active. Please click Forgot Password.';
			$("#login_error").html(result);
			$(".login_form_msg").slideUp("fast");	
			var t=setTimeout(slideErrorDown, 500);
			document.getElementById("passwordForm").focus()
			var t=setTimeout(slideErrorUp, 5000);
			//$.prompt('Your Account Is Not Active. Please click the "Forgot Password" option to resend the activation email and set your password.',{show:'slideDown'});
			return false;
		}
	return false;
}


function resetpassword()
{
		//var login = setTimeout("document.getElementById('errorHolder').style.display = 'none';", 4000);
		var username = document.getElementById("emailForm").value;
		
		if(!username)
		{
			var result = 'Please enter your Email to reset your password.';
			$("#login_error").html(result);
			$(".login_form_msg").slideUp("fast");	
			$(".login_form_error").slideDown("slow");

			var t=setTimeout(slideErrorUp, 5000);
			
			document.getElementById("emailForm").focus();

			//document.getElementById("emailForm").focus();
			//$.prompt(result,{show:'slideDown'});
			//document.getElementById('errorHolder').style.display = '';
		}
		else 
		{
			var resetPasswordReply = getallajax('action=resetPassword&username='+username);	
			if(resetPasswordReply)
			{
				$("#login_error").html(resetPasswordReply);
				$(".login_form_msg").slideUp("fast");	
				$(".login_form_error").slideDown("slow");
	
				var t=setTimeout(slideErrorUp, 5000);
				
				document.getElementById("emailForm").focus();
				//$.prompt(resetPasswordReply,{show:'slideDown'});
				//document.getElementById('errorHolder').style.display = '';
			}
		}
}
