$j(function() {
	$j(".tabs").tabs();
 
	$j("#masthead .drop-down").hoverIntent(function(){
	  $j("#masthead .expand").slideDown("fast");
	}, function() {
	  $j("#masthead .expand").slideUp("fast");
	});
	$j("#masthead .drop-down1").hoverIntent(function(){
	  $j("#masthead .expandhealth").slideDown("fast");
	}, function() {
	  $j("#masthead .expandhealth").slideUp("fast");
	});
	$j("#masthead .drop-down2").hoverIntent(function(){
	  $j("#masthead .expanddrink").slideDown("fast");
	}, function() {
	  $j("#masthead .expanddrink").slideUp("fast");
	});
	$j("#masthead .drop-down3").hoverIntent(function(){
	  $j("#masthead .expandBrand").slideDown("fast");
	}, function() {
	  $j("#masthead .expandBrand").slideUp("fast");
	});
	$j("#masthead .drop-down4").hoverIntent(function(){
	  $j("#masthead .expandforum").slideDown("fast");
	}, function() {
	  $j("#masthead .expandforum").slideUp("fast");
});
$j("#masthead .drop-down5").hoverIntent(function() {
    $j("#masthead .expandmore").slideDown("fast");
}, function() {
    $j("#masthead .expandmore").slideUp("fast");
});

$j("#masthead .drop-down6").hoverIntent(function() {
    $j("#masthead .expandplace").slideDown("fast");
}, function() {
    $j("#masthead .expandplace").slideUp("fast");
});

$j("#masthead .drop-down7").hoverIntent(function() {
    $j("#masthead .expandarticle").slideDown("fast");
}, function() {
$j("#masthead .expandarticle").slideUp("fast");
});

$j("#masthead .drop-down8").hoverIntent(function() {
$j("#masthead .expandproviderP").slideDown("fast");
}, function() {
$j("#masthead .expandproviderP").slideUp("fast");
});

   
	jQuery.fn.fadeToggle = function(speed, easing, callback) {
	  return this.animate({opacity: 'toggle'}, speed, easing, callback);
	}; 
 
	$j(".expand-link").click(function(){
	  $j(".popup").fadeToggle("fast");
	});
	
//	$j('body').click(function() {
// 	  $j("#login-panel").fadeOut("fast");
// 	});

// 	$j('#n-login').click(function(event){
//	  event.stopPropagation();
//	});
//	
//	$j('input.suggested_text, textarea.suggested_text').addClass("field-inactive");
//	$j('input.suggested_text, textarea.suggested_text').focus(function() {
//		$j(this).removeClass("field-inactive").addClass("field-active");
//	    if (this.value == this.defaultValue){ 
//	    	this.value = '';
//		}
//		if(this.value != this.defaultValue){
//			this.select();
//		}
//	});
//	$j('input.suggested_text, textarea.suggested_text').blur(function() {
//	    if ($j.trim(this.value) == ''){
//	    	this.value = (this.defaultValue ? this.defaultValue : '');
//			$j(this).removeClass("field-active").addClass("field-inactive");
//		}
//	});


  // Prevenging double submits of all forms for 5 seconds
  //  - Move to a delegated event when we upgrade jQuery
//  $j('form').submit(function(event) {
//    var form = $j(this);
//    if (form.attr('disabled')){
//      event.preventDefault();
//      return false;
//    }
//    setTimeout(function() { form.attr('disabled', 'disabled'); }, 1);
//    setTimeout(function() { form.removeAttr('disabled');       }, 5000);
//  });


  // Handeling S3 images that have a queued task waiting to be processed
  //(function($, undefined){

//    var IMAGE_LOAD_TIMEOUT = 3000, //ms
//        processing_images  = {},
//        overlay_template   = $('<div class="processing-image-overlay"></div>');

   // findProcessingImages();

//    function findProcessingImages(){
//      processing_images = {};
//      $('img[src*="#processing"]').each(function(){
//        var image = $j(this), src = image.attr('src').replace('#processing', '');
//        if (src in processing_images); else processing_images[src] = $([]);
//        processing_images[src].push(this);
//      });
//      checkImages();

//      setTimeout(findProcessingImages, IMAGE_LOAD_TIMEOUT);
//    }

//    function displayLoadingStatus(images){
//      images.each(function(){
//        var img    = $(this),
//            height = img.height(),
//            width  = img.width();

//        if (height < 5 || width < 5 || img.data('overlay')) return;

//        img.data('overlay',
//          overlay_template.clone()
//            .data('img',img)
//            .css(img.position())
//            .css({
//              margin: img.css('margin'),
//              height: height - 1,
//              width:  width - 1
//            })
//        );

//        if (height < 20 || width < 20) img.data('overlay').addClass('small');

//        img.offsetParent().append( img.data('overlay') );

//        img.css('visibility','hidden');
//      });

//    }
//    function hideLoadingStatus(images){
//      images.each(function(){
//        var img     = $(this),
//            overlay = $(this).data('overlay');

//        img.css('visibility','visible');

//        if (overlay) overlay.remove();
//      });
//    }

//    function checkImages(){
//      $.each(processing_images, function(src, images){
//          var image     = new Image,
//              src_now   = src+'?'+(new Date).getTime(),
//              timed_out = false,
//              timeout_id;

//          function onLoad(){
//            if (timed_out) return;
//            clearTimeout(timeout_id);
//            hideLoadingStatus(images);
//            images.attr('src', src_now);
//          }

//          function onTimeout(){
//            timed_out = true;
//            displayLoadingStatus(images);
//          }

//          image.onload = onLoad;
//          timeout_id   = setTimeout(onTimeout, IMAGE_LOAD_TIMEOUT);
//          image.src    = src_now;
//      });
//    }

 // })(jQuery);

});

//function advSearch() {
//	if((document.getElementById("advancedSearch").style.display == "none") || (!document.getElementById("advancedSearch").style.display)) {
//		document.getElementById("advancedSearch").style.display = "block";
//		document.getElementById("advancedSearchSwitch").style.display = "none";
//		document.getElementById("simpleSearchSwitch").style.display = "block";
//	}
//	else {
//		document.getElementById("advancedSearch").style.display = "none";
//		document.getElementById("advancedSearchSwitch").style.display = "block";
//		document.getElementById("simpleSearchSwitch").style.display = "none";
//	}
//}

//function showUpdatingPopup() {
//	if(!document.getElementById("updater-wheel")) {return false;}
//	var ScrollTop = document.body.scrollTop;
//	if (ScrollTop == 0) {
//		if (window.pageYOffset) {ScrollTop = window.pageYOffset;}
//		else {ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
//	
//	}
//	popup = document.getElementById("updater-wheel");
//	popup.style.left = '50%';
//	popup.style.top = '50%';
//	popup.style.display = "block";
//}
//function hideUpdatingPopup() {
//	if(!document.getElementById("updater-wheel")) {return false;}
//	document.getElementById("updater-wheel").style.display = "none";
//}
//function showSearchingPopup() {
//	if(!document.getElementById("searching_gif")) {return false;}
//	var ScrollTop = document.body.scrollTop;
//	if (ScrollTop == 0) {
//		if (window.pageYOffset) {ScrollTop = window.pageYOffset;}
//		else {ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
//	
//	}
//	var width = (screen.width - 150) / 2;
//	var height = screen.height / 2 - 200;
//	popup = document.getElementById("searching_gif");
//	popup.style.left = width + 'px';
//	popup.style.top = height + 'px';
//	popup.style.display = "block";
//}
//function hideSearchingPopup() {
//	if(!document.getElementById("searching_gif")) {return false;}
//	document.getElementById("searching_gif").style.display = "none";
//}
//function showProcessingDonationPopup() {
//	if(!document.getElementById("processing_donation_gif")) {return false;}
//	var ScrollTop = document.body.scrollTop;
//	if (ScrollTop == 0) {
//		if (window.pageYOffset) {ScrollTop = window.pageYOffset;}
//		else {ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
//	
//	}
//	var width = (screen.width - 450) / 2;
//	var height = screen.height / 2 - 200;
//	popup = document.getElementById("processing_donation_gif");
//	popup.style.left = width + 'px';
//	popup.style.top = height + 'px';
//	popup.style.display = "block";
//}
//function hideProcessingDonationPopup() {
//	if(!document.getElementById("processing_donation_gif")) {return false;}
//	document.getElementById("processing_donation_gif").style.display = "none";
//}

//function selectAllInvites() {
//	checkboxes = $('delete_invites_form').getElementsByTagName("input");

//	for(var i = 0; i < checkboxes.length; i++) {
//		if(checkboxes[i].type == 'checkbox' && checkboxes[i].name == 'invitation_ids[]') {
//			checkboxes[i].checked = true;
//		}
//	} 
//	if($('delete_all_invites')) { Element.show('delete_all_invites'); }
//}

//function unselectAllInvites() {
//	checkboxes = $('delete_invites_form').getElementsByTagName("input");

//	for(var i = 0; i < checkboxes.length; i++) {
//		if(checkboxes[i].type == 'checkbox' && checkboxes[i].name == 'invitation_ids[]') {
//			checkboxes[i].checked = false;
//		}
//	} 
//	if($('delete_all_invites')) { Element.hide('delete_all_invites'); }
//}

//function inviteUnselected() {
//	$('select_all').checked = false;
//	if($('delete_all_invites')) { Element.hide('delete_all_invites'); }
//}

//function showReportPopup(obj) {
//	var popup = document.getElementById(obj.id+"p");
//	popup.style.left = findPosX(obj) + 'px';
//	popup.style.top = findPosY(obj) + 16 + 'px';
//	document.body.appendChild(popup);
//	popup.style.display = "block";
//}
//function closeReportPopup(obj) {
//	//document.getElementById("bg").style.display = "none";
//	obj.parentNode.style.display = "none";
//}
//function showHelp(obj) {
//	var popup = document.getElementById(obj.id+"p");

//	xPos = findPosX(obj);
//	var offset = Math.ceil(306 - (windowWidth()/2 + 480 - xPos));
//	offset = Math.max(offset, 20);
//	xPos = xPos - offset;
//	
//	popup.style.left = xPos + 'px';
//	popup.style.top = (findPosY(obj)+20) + 'px';
//	popup.style.display = "block";
//	popup.onclick = function() {this.style.display = "none";}
//}
//function showCommonHelp(obj, popupId) {
//	var popup = document.getElementById(popupId);
//	popup.style.left = findPosX(obj) - 20 + 'px';
//	popup.style.top = findPosY(obj) + 'px';
//	popup.style.display = "block";
//	popup.onclick = function() {this.style.display = "none";}
//}

//function showPopup(id, scrolling) {
//	lightboxPopup("pop-up-" + id, scrolling);
//}
//function lightboxPopup(id, scrolling) {
//	if(!document.getElementById(id)) {return false;}

//	if($("black") == null) {
//		var black = document.createElement('div');
//		black.id = "black";
//		black.style.height = (document.body.offsetHeight+50) + 'px';
//		document.getElementsByTagName("body")[0].appendChild(black);
//	}

//	if($('vid-embed')) { $('vid-embed').style.visibility = 'hidden'; }
//	var popup = document.getElementById(id);

//	if(oldBrowser()) {scrolling = 'absolute';}

//	if(scrolling == undefined || scrolling == null || scrolling == 'fixed') {
//		popup.style.position = 'fixed';
//		popup.style.display = "block";
//		offsetHeight = Math.floor((document.documentElement.clientHeight - popup.offsetHeight) / 2);
//		popup.style.top = offsetHeight + 'px';
//	} else {
//		popup.style.top = windowYOffset() + 150 + 'px';
//		popup.style.position = 'absolute';
//		popup.style.display = "block";
//	}	
//}
//function hidePopup(id) {
//	hideLightboxPopup("pop-up-" + id);
//}
//function hideLightboxPopup(id) {
//	if(!document.getElementById(id)) {return false;}

//	var black = document.getElementById("black");
//	document.getElementsByTagName("body")[0].removeChild(black);
//	black.style.display = "none";

//	if($('vid-embed')) { $('vid-embed').style.visibility = 'visible'; }
//	document.getElementById(id).style.display = "none";
//}
//function showLockedPopup(obj, user_id) {
//	if($('private_popup_link'))
//		$('private_popup_link').href = '/people/add_friend?friend_id=' + user_id;
//	var popup = document.getElementById("lockedUserp");
//      popup.style.left = findPosX(obj) + 'px';
//	popup.style.top = findPosY(obj) + 16 + 'px';
//	document.body.appendChild(popup);
//	popup.style.display = "block";
//}
//function showComplimentPopup(context, recipient_id, recipient_name, complimentable_id) {
//	$('complimentRecipientName').innerHTML = recipient_name;
//	$('complimentForm').complimentText.value = '';
//	$('complimentForm').complimentContext.value = context;
//	$('complimentForm').complimentRecipient.value = recipient_id;
//	$('complimentForm').complimentableID.value = complimentable_id;
//	showPopup('complimentForm');
//}
//function closeComplimentPopup() {
//	hidePopup('complimentForm');
//	$('complimentForm').complimentText.value = '';
//	$('complimentBody').innerHTML = '';
//}
//function disableComplimentButtons() {
//	$('complimentForm').elements['send'].disabled = true;
//	$('complimentForm').elements['cancel'].disabled = true;
//}
//function enableComplimentButtons() {
//	$('complimentForm').elements['send'].disabled = false;
//	$('complimentForm').elements['cancel'].disabled = false;
//}
//function disableSubmit() {
//	$('submit_payment').disabled = true;
//	$('cancel_payment').disabled = true;
//}
//function enableSubmit() {
//	$('submit_payment').disabled = false;
//	$('cancel_payment').disabled = false;
//}
//function switchToReplyEditor(id) {
//	tinyMCE.execCommand("mceAddControl", false, "comment_comment_"+id);

//	if($('threadReplyLink'+id)) {Element.hide('threadReplyLink'+id);}    
//	Element.show('replyForm' + id); 
//	Element.hide('commentForm');
//}
//function switchToCommentEditor(id) {
//	Element.hide('replyForm' + id);
//	if($('threadReplyLink'+id)) {Element.show('threadReplyLink'+id);}   
//	Element.show('commentForm');        
//}
//function windowWidth() {
//	return document.documentElement && document.documentElement.clientWidth || document.body && document.body.clientWidth || document.body && document.body.parentNode && document.body.parentNode.clientWidth || 0;
//}
//function windowYOffset() {
//	if(window.pageYOffset)
//		return window.pageYOffset;
//	else
//		return (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
//}
//function findPosY(obj) {
//	var posTop = 0;
//	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
//	return posTop;
//}
//function findPosX(obj) {
//	var posLeft = 0;
//	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
//	return posLeft;
//}
//function checkFieldLength(fieldID, counterID, maxLength) {
//	if($(fieldID)) {
//		content = $(fieldID).value;
//		length = content.length;

//		if(length > maxLength) {
//			$(fieldID).value = content.substring(0, maxLength);
//			length = maxLength;
//		} 
//		
//		if($(counterID)) {
//			$(counterID).innerHTML = (maxLength - length);
//		}
//	}
//}
//function askCommentFocus(askID) {
//	formID = 'askResponse' + askID;
//	if($(formID)) {
//		comment_field = $(formID).comment_comment;
//		comment_field.style.height = '30px';
//		comment_field.style.color = '#000';
//		if(comment_field.value == 'Write a comment') { comment_field.value = ''; }
//		comment_field.focus();

//		$('askResponseSubmit' + askID).style.display = 'block';
//	}
//}
//function askCommentFocusLost(askID) {
//	formID = 'askResponse' + askID;
//	if($(formID)) {
//		comment_field = $(formID).comment_comment;
//		if(comment_field.value == '') {
//			comment_field.style.height = '15px';
//			comment_field.style.color = '#666666';
//			comment_field.value = 'Write a comment';
//			$('askResponseSubmit' + askID).style.display = 'none';
//		}
//	}
//}
//function replaceExtChars(text) {
//	fromTo = new Array('&amp;', '&', '&gt;','>','&lt;','<','&quot;','\"');

//	for(i=0; i < fromTo.length; i=i+2) {
//		text = text.replace(eval('/'+fromTo[i+1]+'/g'), fromTo[i]);
//	}
//	
//	return text;
//}
//function profileNoteFocus(defaultText) {
//	if($('profileNote')) {
//		comment_field = $('profileNote').comment_comment;
//		//comment_field.style.height = '60px';
//		comment_field.style.color = '#000';
//		if(comment_field.value == defaultText) { comment_field.value = ''; }
//		comment_field.focus();
//		//$('profileNoteSubmit').style.display = 'inline';
//		//$('character-count').style.display = 'block';
//	}
//}
//function profileNoteFocusLost(defaultText) {
//	if($('profileNote')) {
//		comment_field = $('profileNote').comment_comment;
//		if(comment_field.value == '') {
//			//comment_field.style.height = '15px';
//			comment_field.style.color = '#666666';
//			comment_field.value = defaultText;
//			//$('profileNoteSubmit').style.display = 'none';
//			//$('character-count').style.display = 'none';
//		}
//	}
//}

///// Petition Target Selection

//function numCheckedBoxesOfGivenClass(node, searchClass) {
//	var els = node.getElementsByTagName('input');

//	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
//	var numChecked = 0;
//	for (i = 0, j = 0; i < els.length; i++) {
//		if ( pattern.test(els[i].className) && els[i].type == 'checkbox') {
//			if(els[i].checked)
//				numChecked += 1;
//		}
//	}
//	return numChecked;
//}
//function getIEVersionNumber() {
//    var ua = navigator.userAgent;
//    var MSIEOffset = ua.indexOf("MSIE ");
//    
//    if (MSIEOffset == -1) {
//        return null;
//    } else {
//        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
//    }
//}
//function oldBrowser() {
//	ieVersion = getIEVersionNumber();
//	if(ieVersion && ieVersion <= 6)
//		return true;
//	else if(navigator.appVersion.indexOf('Safari') >= 0 && navigator.appVersion.indexOf('Version/2.') >= 0)
//		return true;
//	else
//		return false;
//}
//function getCheckedValue(radioObj) {
//	if(!radioObj)
//		return "";
//	var radioLength = radioObj.length;
//	if(radioLength == undefined)
//		if(radioObj.checked)
//			return radioObj.value;
//		else
//			return "";
//	for(var i = 0; i < radioLength; i++) {
//		if(radioObj[i].checked) {
//			return radioObj[i].value;
//		}
//	}
//	return "";
//}
//function getTextAreaSelection(txtarea)
//{
//	txt = '';
//	if (typeof txtarea.selectionStart != "undefined") {
//		txt = (txtarea.value).substring(txtarea.selectionStart, txtarea.selectionEnd);
//	} else if (document.selection)
//    { txt = document.selection.createRange().text; }

//	return txt;
//}
//function disableButton(button){
//	button.style.cursor = 'default';
//	button.onclick = doNothing;
//}
//function doNothing() { return false; }
//	
//function addLoadEvent(func) {
//  var oldonload = window.onload;
//  if (typeof window.onload != 'function') {
//    window.onload = func;
//  } else {
//    window.onload = function() {
//      if (oldonload) {
//        oldonload();
//      }
//      func();
//    }
//  }
//}
//function loadScript(src, id) {
//  var e = document.createElement('script'); 
//  e.setAttribute('language','javascript'); 
//  e.setAttribute('type', 'text/javascript');
//  e.setAttribute('src',src);
//  if(id != null) e.setAttribute('id',id);
//  document.getElementsByTagName('head')[0].appendChild(e); 
//}
//function loadCSS(src, id) {
//  var e = document.createElement('link'); 
//  e.setAttribute('rel', 'stylesheet'); 
//  e.setAttribute('type', 'text/css');
//  e.setAttribute('href',src);
//  if(id != null) e.setAttribute('id',id);
//  document.getElementsByTagName('head')[0].appendChild(e); 
//}


// GOOGLE ANALYTICS
//var GA = {};
//GA.trackPageview = function(pageview) {
//  if (typeof(ga_pagetracker) === 'undefined') return false;
//  ga_pagetracker._setCustomVar(1, 'UserType', ENV['GA_USER_TYPE'], 2);
//  ga_pagetracker._trackPageview(pageview);
//};



// PETITION SHARE RELATED
var SharePopup = {};

;(function(){

  var currentActionTitle, currentActionId, currentShareKey, currentPopupId, currentGAInfo, twitterWindow;

//  SharePopup.registerTwitterShare = function (eventId, title, url, shareKey, count, gaInfo) {
//    currentTwitterTitle = title;
//    currentGAInfo = gaInfo;

//    twitterWindow = window.open('', 'twitter', 'height=400,width=800');
//    loadScript("http://api.bit.ly/shorten?version=2.0.1&login="+ENV['BITLY_LOGIN']+"&apiKey="+ENV['BITLY_API_KEY']+"&callback=SharePopup.bitlyResponse&longUrl=" + url);

//    new Ajax.Updater('dummy', '/actions/register_external_share?location=twitter&event_id='+eventId+'&context=pageshare&share_key=' + shareKey, {
//      asynchronous: true,
//      evalScripts: true
//    });
//    GA.trackPageview('/goal/petition/shared/twitter?'+currentGAInfo);
//    if($('tweetCount'+eventId)) $('tweetCount'+eventId).innerHTML = count+1;
//  };

//  SharePopup.bitlyResponse = function(data) {
//    var first_result;
//    // Results are keyed by longUrl, so we need to grab the first one.
//    for(var r in data.results) {
//      first_result = data.results[r]; break;
//    }
//    shortUrl = first_result.shortUrl;
//    twitterStatus = 'Sign Petition @change: '+currentTwitterTitle+' '+ shortUrl;
//    popupTwitterUrl = 'http://twitter.com/home?status=' + encodeURIComponent(twitterStatus);
//    twitterWindow.location = popupTwitterUrl;
//  };

//  SharePopup.showFacebookFeedDialog = function(eventID, title, url, imageUrl, shareKey, count, gaInfo) {
//    currentActionId = eventID;
//    currentShareKey = shareKey;
//    currentGAInfo = gaInfo;

//    attachment = {'name':title,'href':url,'caption':'{*actor*} is helping recruit people to sign this petition. Help by lending your voice!','media':[{'type':'image','src':imageUrl,'href':url}]};
//    actionLinks = [{'text':'Sign the Petition','href':url}];
//    FB.Connect.streamPublish('', attachment, actionLinks, '', 'Why do you support this petition?', SharePopup.registerFacebookShare, false);

//    if($('fbCount'+eventId)) $('fbCount'+eventID).innerHTML = count+1;
//  };

//  SharePopup.registerFacebookShare = function(post_id, exception, data) {
//    if (post_id) {
//      new Ajax.Updater('dummy', '/actions/register_external_share?location=facebook&event_id='+currentActionId+'&context=pageshare&share_key='+currentShareKey, {
//        asynchronous: true,
//        evalScripts: true
//      });
//      GA.trackPageview('/goal/petition/shared/facebook?'+currentGAInfo);
//    }
//  };

  SharePopup.displayPopup = function(popupId, link, gaInfo) {
    currentPopupId = popupId;

    //if($('bitlyUrl'+popupId).value == '')
    //loadScript("http://api.bit.ly/shorten?version=2.0.1&login="+ENV['BITLY_LOGIN']+"&apiKey="+ENV['BITLY_API_KEY']+"&callback=SharePopup.setBitlyUrl&longUrl=" + link);

    $j("#sharePopup"+popupId).fadeIn("fast");
  };

//  SharePopup.setBitlyUrl = function(data) {
//	var first_result;
//    // Results are keyed by longUrl, so we need to grab the first one.
//    for(var r in data.results) {
//      first_result = data.results[r]; break;
//    }
//    shortUrl = first_result.shortUrl;

//    if($('bitlyUrl'+currentPopupId)) {
//      $('bitlyUrl'+currentPopupId).value = shortUrl;
//    }
//  };

})();
