
String.prototype.startsWith = function(prefix) {
    return this.indexOf(prefix) === 0;
};

//temporarily disabled
//function target_links() {}

//attaches interstitial function for all outgoing links
function target_links() {

    $("a").each( function(x) {

	var destination = $(this).attr("href");
    
	if(!destination) return;
	if(destination.match(/https?:\/\/(.*\.)?thinksciencenow.com/)) return;
        if(destination.startsWith('http://') || destination.startsWith('https://')) {

        	var edestination = destination.replace(/https?:\/\/([^\/]+).*/, "$1");
        	if(edestination != document.domain) {
				if (destination.match(/https?:\/\/(.*\.)?pfizer.com/) || destination.match(/https?:\/\/(.*\.)addthis.com/)) {
					$(this).attr('target', '_blank');
					return;
				} else {
                	$(this).attr('href','javascript:externallink(\''+destination+'\')');
                }
            }
        }});
}

function showEmbeds(tf) {
	//toggle display of embedded videos and such to prevent overlapping display issue in IE.
	//if ($.browser.msie) {
		if (tf == true) {
			$('embed').each ( function() {
				$(this).css('display','block');
			});
			$('object').each ( function() {
				$(this).css('display','block');
			});
			$('iframe').each (function() {
				$(this).css('display','block');
			});
		} else if (tf == false) {
			$('embed').each ( function() {
				$(this).css('display','none');
			});
			$('object').each ( function() {
				$(this).css('display','none');
			});
			$('iframe').each (function() {
				$(this).css('display','none');
			});
		}
	//}
}


//interstitial function; uses jQuery UI Dialog
function externallink(destination) {
	$('#targetlink').html(destination);
	$("#external_warning").dialog("option", "buttons", { "Cancel": function() { $(this).dialog("close"); showEmbeds(true); }, "Confirm": function() { $(this).dialog("close"); window.open(destination); }} );
	$('#external_warning').bind('dialogclose', function(event, ui) {
		showEmbeds(true);
	 }); //shows embedded content on hitting the (x) button in intersitital
	$('div#external_warning h2.external-title').html('You are leaving Think Science Now');
	$('div#external_warning h2.external-title').css('font-size', '');
	$('div#external_warning p.external-message').html(
		"You are now leaving ThinkScienceNow.com. Links to sites outside of Pfizer are provided as a resource to the viewer. Pfizer accepts no responsibility for the content of linked sites."
	);

	
	//style the buttons by adding classes


	var dialog = $("#external_warning").parents(".ui-dialog.ui-widget");
	var buttons = dialog.find(".ui-dialog-buttonpane").find("button");
	$(buttons[0]).attr('alt', 'Cancel');
	$(buttons[0]).addClass("modal-cancel");
	$(buttons[1]).attr('alt', 'Confirm');
    $(buttons[1]).addClass("modal-confirm");
	$('span.ui-button-text').html('');

	//append a bottom div to the dialog (will contain the bottom border)
	
	if (dialog.children('div.modal-bottom').length == 0) {
		dialog.append('<div class="modal-bottom"></div>');
	} else {
		//the bottom div seems to migrate on its own if it stays put, so removing it and adding a new one as needed
		dialog.children('div.modal-bottom').remove();
		dialog.append('<div class="modal-bottom"></div>');
	}
	
	$("#external_warning").dialog("option", "width", '379px');
	
	//hide embeds, then open
	showEmbeds(false);
	
	$('#external_warning').dialog('open');
	
	
//    window.location.href="/widstrip/external.html?origin="+
 //       encodeURIComponent(window.location)+"&target="+encodeURIComponent(destination);
}

//translating newsletter plugin php validation to javascript; includes translation of is_email()
function email_valid(emailstring) {
	//make everything lowercase
	emailstring = emailstring.toLowerCase();
	
	// Test for the minimum length the email can be
	//if ( strlen( emailstring ) < 3 ) {
	if (emailstring.length < 3) {
		return false;
	}

	// Test for an @ character after the first position
	if (emailstring.indexOf('@', 1) == -1) {
		return false;
	}

	// Split out the local and domain parts
	var local;
	var domain;
	var parts = emailstring.split('@', 2);
	local = parts[0];
	domain = parts[1];

	// LOCAL PART
	// Test for invalid characters
	var reInv = /^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/;
	if (!reInv.test(local)) {
		return false;
	}

	// DOMAIN PART
	// Test for sequences of periods

	var reDom = /\.{2,}/;
	if (reDom.test(domain)) {
		return false;
	}

	// Test for leading and trailing periods and whitespace
	var trimmedDom = $.trim(domain);
	trimmedDom = trimmedDom.replace(/[.{1,}]+$/, "");
	if (trimmedDom !== domain) {
		return false;
	}

	// Split the domain into subs
	var subs = domain.split('.');
	// Assume the domain will have at least two subs
	if ( 2 > subs.length ) {
		return false;
	}

	// Loop through each sub
	for (var i = 0 ; i < subs.length ; i++) {
		//length should be at least 1 character
		if (subs[i].length < 1) {
			return false;
		}
		// Test for leading and trailing hyphens and whitespace
		//no native js trim, so using jQuery
		if ($.trim(subs[i]) !== subs[i]) {
				return false;
		}
		// Test for invalid characters
		var reInvSub = /^[a-z0-9-]+$/i;
		if (!reInvSub.test(subs[i])) {
				return false;
		}
	}
	return true;
}

function subscribe(event, form) {
	//prevent bubble up
	event.stopPropagation();
	//from newsletter plugin: check for valid email 
	var re = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-]{2,})+\.)+([a-zA-Z0-9]{2,})+$/;
	//if it doesn't match wp's validation or the plugin's validation, reject
	if (!email_valid(form.elements["ne"].value) /*|| !re.test(form.elements["ne"].value)*/) {
        //alert("Oops! This email address is invalid. Please check for errors and try again.");
		pfizer_alert("Oops!", "This email address is invalid. Please check for errors and try again.");
		event.preventDefault();
        return false;
    } else {
		//change messages
		$('div#external_warning h2.external-title').html('Thank You for Subscribing!');
		$('div#external_warning h2.external-title').css('font-size', '16pt');
		$('div#external_warning p.external-message').html('Please confirm you would like to receive the Think Science Now newsletter containing the most popular blogs from Think Science Now.');
		$("#external_warning").dialog(
			"option",
			"buttons",
			{
			"Cancel": function() {
							event.preventDefault();
							$(this).dialog("close");
							showEmbeds(true);
							return false;
						},
			"Confirm": function() {
							//submit the form by unbinding the submit event from the form and then resubmitting.
							$(form).unbind();
							$(form).submit();
							return true;							
						}
			}
		);
		$('#external_warning').bind('dialogclose', function(event, ui) {
			showEmbeds(true);
		 }); //shows embedded content on hitting the (x) button in intersitital
		//style the buttons by adding classes
		var dialog = $("#external_warning").parents(".ui-dialog.ui-widget");
		var buttons = dialog.find(".ui-dialog-buttonpane").find("button");
		$(buttons[0]).attr('alt', 'Cancel');
		$(buttons[0]).addClass("modal-cancel");
		$(buttons[1]).attr('alt', 'Confirm');
		$(buttons[1]).addClass("modal-confirm");
		$(buttons).addClass("newsletter-modal");
		$('span.ui-button-text').html('');
		
		//append disclaimer underneath buttons
		dialog.find(".ui-dialog-buttonpane").addClass("disclaimer");
		dialog.find(".ui-dialog-buttonpane").append(
			'<p class="modal-disclaimer">' +
			"Your email address is provided for Pfizer's use only and will be kept strictly confidential. Your email address will not be shared with any third party solicitors." +
			'</p>'
		);
		
		if (dialog.children('div.modal-bottom').length == 0) {
			dialog.append('<div class="modal-bottom"></div>');
		} else {
			//the bottom div seems to migrate on its own if it stays put, so removing it and adding a new one as needed
			dialog.children('div.modal-bottom').remove();
			dialog.append('<div class="modal-bottom"></div>');
		}
		$("#external_warning").dialog("option", "width", '379px');
		
		//hide embeds for interstitial
		showEmbeds(false);
		
		$('#external_warning').dialog('open');
		event.preventDefault();
	}
}

//use the styled interstitial instead of a standard alert dialogue
function pfizer_alert(header,message) {
	$("#external_warning").dialog("option", "buttons", { "Go": function() { $(this).dialog("close"); showEmbeds(true); }});
	$('#external_warning').bind('dialogclose', function(event, ui) {
		showEmbeds(true);
	 }); //shows embedded content on hitting the (x) button in intersitital
	$('div#external_warning h2.external-title').html(header);
	$('div#external_warning h2.external-title').css('font-size', '');
	$('div#external_warning p.external-message').html(message);
	
	//style the buttons by adding classes
	var dialog = $("#external_warning").parents(".ui-dialog.ui-widget");
	var buttons = dialog.find(".ui-dialog-buttonpane").find("button");
	$(buttons[0]).attr('alt', 'Go');
	$(buttons[0]).addClass("modal-go");
	$('span.ui-button-text').html('');

	//append a bottom div to the dialog (will contain the bottom border)
	if (dialog.children('div.modal-bottom').length == 0) {
		dialog.append('<div class="modal-bottom"></div>');
	} else {
		//the bottom div seems to migrate on its own if it stays put, so removing it and adding a new one as needed
		dialog.children('div.modal-bottom').remove();
		dialog.append('<div class="modal-bottom"></div>');
	}
	
	$("#external_warning").dialog("option", "width", '379px');
	
	//hide embeds, then open
	showEmbeds(false);
	
	$('#external_warning').dialog('open');
}

function wrap_embeds() {
	//wrap embeds in Divs to allow toggleEmbeds to hide embedded videos on interstitial
	//also ensure max-width of player does not exceed size of content area (will use 560px as max-width)
	
	$('embed').each( function () {
		$(this).css('max-width','560px');
		$(this).css('max-height', 'auto');
		$(this).wrap('<div>');
		$(this).parent('div').css('max-height', $(this).css('max-height'));
		$(this).parent('div').css('max-width', $(this).css('max-width'));
	});
	
	$('object').each(function () {
		$(this).wrap('<div>');
		if ($.browser.webkit) {
			$(this).parent('div').css('height', $(this).height());
			$(this).parent('div').css('width', $(this).width());	
		} else {
			$(this).parent('div').css('height',$(this).css('height') );
			$(this).parent('div').css('width', $(this).css('width'));
		}
	});
	//end embed fix	
}

$(document).ready(function() {	 
	setTimeout("wrap_embeds()", 500);

	$('input#input_1_1').example('Your email here');
	$("div.comment-trigger div#comments").hide();
	$('div.comment-trigger div.comment-trigger p').click(function() {
		$('div#comments').slideToggle('slow', function() {
		// Animation complete.
		});
	});
	 $("h2.title").hover(function () {
		$(this).addClass('hover');
	}, 
	function () {
		$(this).removeClass("hover");
	});
	$('h2.trigger').click(function() {
		if ($(this).hasClass('gray')) { 
			$(this).toggleClass('gray-closedup'); } 
		else if ($(this).hasClass('purple')) { 
			$(this).toggleClass('purple-closedup'); } 
		else if ($(this).hasClass('red')) { 
			$(this).toggleClass('red-closedup'); } 
		else if ($(this).hasClass('light-blue')) { 
			$(this).toggleClass('light-blue-closedup'); } 
		else if ($(this).hasClass('royal-blue')) { 
			$(this).toggleClass('royal-blue-closedup'); } 
		else if ($(this).hasClass('green')) { 
			$(this).toggleClass('green-closedup'); } 
		else if ($(this).hasClass('orange')) { 
			$(this).toggleClass('orange-closedup'); } 
		else { $(this).toggleClass('closedup'); }
		$(this).next().slideToggle('slow', function() {
		// Animation complete.
		});
	});
	$("li#recent-posts-custom li.post:last, div.aside li.twitter-3 div.widget-in li:last").addClass('last');
	if ($('div#tabbed').length || $('div.memberwrap').length) { // implies *not* zero
	 	 $("body").addClass('onPeople');
	} else { }
	//$("#search-popular li a").after(",");
	//$("#search-popular li:last").addClass('last');
	$('#slides').cycle({ fx:'fade', speed:'slow', timeout: 7000, pager:  '#pager',
		pagerAnchorBuilder: function(i, el) {
			return '<a href="#" title="'+ $(el).find('a.slideLink').attr('title') +'"><span>' + (i+1) + '</span></a>';
		}});
	$("a.next").html("Next");
	$("a.prev").html("Previous");
	
	$("div#nav li").hover(function () {
		$(this).addClass('hover');
	}, 
	function () {
		$(this).removeClass("hover");
	});

	if($('#featured-profiles-home')) {
		$('#featured-profiles-home').load('/searching/people/featured-members-ajax');
		$('#featured-profiles-sidebar').load('/searching/people/guest-contributors-ajax');
	}

	//$("a[href^=http://science.pfizer.com/]").attr('href').replace('http:','https:');

	target_links();

	$('#external_warning').dialog({ "autoOpen": false, "draggable": false, "height": 240, "modal": true, "resizable": false, "width": 450 });
	
	//bind newsletter interstitial; uses jQuery UI Dialog

	if ($('div.newsletter.newsletter-widget form').length > 0) {
		//var submitButton = $('div.newsletter.newsletter-widget form').children('p').eq(1).children('input');
		
		$('div.newsletter.newsletter-widget form').get(0).onsubmit = null;
		
		//submitButton.click(  //attach the subscribe interstitial to submit event
		$('div.newsletter.newsletter-widget form').submit(
			function (event) {
				subscribe(event, $('div.newsletter.newsletter-widget form').get(0));
			}
		);
	}
	
	//CSS dropdown menu for Home nav button based on http://www.noupe.com/tutorial/drop-down-menu-jquery-css.html
	$("div#topnav-buttons a#home").mouseover(function() {
			//Following events are applied to the subnav itself (moving subnav up and down)  
			$("ul.nav-dropdown-list").slideDown('fast').show(); //Drop down the subnav on click  

			$(this).parent().hover(function() {}, function() {
					$("ul.nav-dropdown-list").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
			});
		}).hover(function() {  
			$(this).addClass("subhover");
		}, function() {
			$(this).removeClass("subhover");
			//$(this).parent().find("ul.nav-dropdown-list").slideUp("slow");
	});
	
	$("span.interest-area-dropdown-side div.dropdown-target").mouseover(function() {
      
            //Following events are applied to the subnav itself (moving subnav up and down)  
            $(this).parent().find("ul.interest-area-dropdown-list").slideDown('fast').show(); //Drop down the subnav on click  
      
            $('span.interest-area-dropdown-side').hover(function() {  
            }, function(){
               $(this).parent().find("ul.interest-area-dropdown-list").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  

            });

            }).hover(function() {
                $(this).addClass("subhover");
            }, function(){
                $(this).removeClass("subhover");
        });
	$("span#interest-area-dropdown-main div.dropdown-target").mouseover(function() {
      
            //Following events are applied to the subnav itself (moving subnav up and down)  
            $(this).parent().find("ul.interest-area-dropdown-list").slideDown('fast').show(); //Drop down the subnav on click  
      
            $('span#interest-area-dropdown-main').hover(function() {  
            }, function(){
                $(this).parent().find("ul.interest-area-dropdown-list").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
            });

            }).hover(function() {
                $(this).addClass("subhover");
            }, function(){
                $(this).removeClass("subhover");
        });
 
	//Tabbed navigation switching; hides the current content, makes visible the selected content, and changes the frame to the right color
	
	//members
	$("div#lower-feature-tabs a#lower-feature-tab-contributors").click(function() {
		$("div#lower-feature-frame-top").removeClass();
		$("div#lower-feature-frame-top").addClass("lower-feature-frame-top-contributors");
		$("div#lower-feature-frame-content").removeClass();
		$("div#lower-feature-frame-content").addClass("lower-feature-frame-content-contributors");
		$("div#lower-feature-frame-btm").removeClass();
		$("div#lower-feature-frame-btm").addClass("lower-feature-frame-btm-contributors");	
		
		//hide all other content, display members content
		$("div#lower-feature-frame-entries-social").css("display", "none");
		$("div#lower-feature-frame-entries-news").css("display", "none");
		$("div#lower-feature-frame-entries-videos").css("display", "none");
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").removeClass();
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("href", $('span#viewall-link-contributors').html());
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("title", $('span#viewall-link-contributors').attr('title'));
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("alt", $('span#viewall-link-contributors').attr('alt'));
		$("div#lower-feature-frame-entries-contributors").css("display", "block");			

		//change breadcrumb
		$("div#crumbs span#header_crumbs").text("Members");
		
	});
	
	//social media
	$("div#lower-feature-tabs a#lower-feature-tab-social").click(function() {
		$("div#lower-feature-frame-top").removeClass();
		$("div#lower-feature-frame-top").addClass("lower-feature-frame-top-social");
		$("div#lower-feature-frame-content").removeClass();
		$("div#lower-feature-frame-content").addClass("lower-feature-frame-content-social");
		$("div#lower-feature-frame-btm").removeClass();
		$("div#lower-feature-frame-btm").addClass("lower-feature-frame-btm-social");		
		
		//hide all other content, display social media content
		$("div#lower-feature-frame-entries-contributors").css("display", "none");
		$("div#lower-feature-frame-entries-news").css("display", "none");
		$("div#lower-feature-frame-entries-videos").css("display", "none");
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").removeClass();
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("href", $('span#viewall-link-social-media').html());
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("title", $('span#viewall-link-social-media').attr('title'));
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("alt", $('span#viewall-link-social-media').attr('alt'));
		$("div#lower-feature-frame-entries-social").css("display", "block");

		//change breadcrumb
		$("div#crumbs span#header_crumbs").text("Social Media");

	});

	//news
	$("div#lower-feature-tabs a#lower-feature-tab-news").click(function() {
		$("div#lower-feature-frame-top").removeClass();
		$("div#lower-feature-frame-top").addClass("lower-feature-frame-top-news");
		$("div#lower-feature-frame-content").removeClass();
		$("div#lower-feature-frame-content").addClass("lower-feature-frame-content-news");
		$("div#lower-feature-frame-btm").removeClass();
		$("div#lower-feature-frame-btm").addClass("lower-feature-frame-btm-news");	
		
		//hide all other content, display news content
		$("div#lower-feature-frame-entries-contributors").css("display", "none");
		$("div#lower-feature-frame-entries-social").css("display", "none");
		$("div#lower-feature-frame-entries-videos").css("display", "none");
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").removeClass();
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("href", $('span#viewall-link-news').html());
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("title", $('span#viewall-link-news').attr('title'));
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("alt", $('span#viewall-link-news').attr('alt'));

		$("div#lower-feature-frame-entries-news").css("display", "block");
		
		//change breadcrumb
		$("div#crumbs span#header_crumbs").text("News");
	});

	//videos
	$("div#lower-feature-tabs a#lower-feature-tab-videos").click(function() {
		$("div#lower-feature-frame-top").removeClass();
		$("div#lower-feature-frame-top").addClass("lower-feature-frame-top-videos");
		$("div#lower-feature-frame-content").removeClass();
		$("div#lower-feature-frame-content").addClass("lower-feature-frame-content-videos");
		$("div#lower-feature-frame-btm").removeClass();
		$("div#lower-feature-frame-btm").addClass("lower-feature-frame-btm-videos");	
	
		//hide all other content, display video content
		$("div#lower-feature-frame-entries-contributors").css("display", "none");
		$("div#lower-feature-frame-entries-social").css("display", "none");
		$("div#lower-feature-frame-entries-news").css("display", "none");
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").removeClass();
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").addClass('video-all');
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("href", $('span#viewall-link-videos').html());
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("title", $('span#viewall-link-videos').attr('title'));
		$("div#lower-feature-frame-content div#lower-feature-viewall-button a#viewall").attr("alt", $('span#viewall-link-videos').attr('alt'));
		$("div#lower-feature-frame-entries-videos").css("display", "block");
		
		//change breadcrumb
		$("div#crumbs span#header_crumbs").text("Videos");
		
	});
	
	//activate scrollbars using jScrollPane
	$('.scroll-pane').jScrollPane({showArrows: true, autoReinitialise: true});

	/*
	//add submit class to newsletter submit button to fix issues in IE
	var newsletterPs = $("div.after div.newsletter").find('p');
	//var htmlstuff = newsletterPs[0].html();
	var submitP = newsletterPs[1];
	$(submitP).addClass('submit');
	*/
});

