/*
#
#authors: Alex Grande & Martin Lovell
#
*/

//
// requiring all fields for validation in forms.
$(".researchMainContent input, .scheduleOptions input").addClass("required");

$("ul#research-signup-medconlist input").removeClass("required");

//
// making all links in the right section popup in a new window regardless if js is enabled.
var rightLinksNoVideo = "ul#clinicalArticles a, div#signup a, div#featuredArticles a";
$(rightLinksNoVideo).attr("target", "_blank");
$(rightLinksNoVideo).attr("rel", "external");

$("a[rel='external']").click(function() {
	window.open(
		$(this).attr("href")
	);
	return false;
});

//
// for new window video links
$('#otherClinicalVideo a').click(function() {
	showVWnd($(this).attr("rel"));
    return false;
});

//
// for sliding down text. cooolness

var Slider = function() {}

	//things to start up go here.
	Slider.prototype = {
		initialize: function(toggleEvent, slider, clientWrapper){
			this.toggleEvent = toggleEvent;
			this.slider = slider;
			this.clientWrapper = clientWrapper;
			this.toggleSlideDown(this.toggleEvent, this.slider, this.clientWrapper);
		},
		
		toggleSlideDown: function(toggleEvent, slider, clientWrapper){
		
			// This the total height of the study description without overflow:hidden
			var $totalHeight = document.getElementById(slider).scrollHeight;
			// This the viewable height of the study description with overflow:hidden
			var $viewableHeight = document.getElementById(slider).clientHeight;
			// This is the total height of the element that wraps around the study description
			var $wrapperTotalHeight = document.getElementById(clientWrapper).clientHeight;
			// This is how much the wrapper element needs to grow with the study description
			var $wrapperAddHeight = $totalHeight - $viewableHeight;
			// This is the total value in which it will increase
			var $wrapperToIncrease = $wrapperTotalHeight + $wrapperAddHeight;
			
			$(toggleEvent).toggle(function(){
			// this "close" is a temporary fix to get the study description on the PRP to change text when you click it. 
		//		$(this).html("close");
				$('#' + slider).animate({
					height: $totalHeight
				}, 1000), $('#' + clientWrapper).animate({
					height: $wrapperToIncrease
				}, 1000)
				
			}, function(){
			// Same with this one too
		//	$(this).html("Read more...");
				$('#' + slider).animate({
					height: $viewableHeight
				}, 1000), $('#' + clientWrapper).animate({
					height: $wrapperTotalHeight
				}, 1000)
			});
		}
	}



//
// for links that are not links. like <span> that needs to act like an <a>

$(".thisIsALink").hover(function () {
    $(this).css({textDecoration:"underline"});
    }, function () {
      $(this).css({textDecoration:"none"});
    });
	


		


//
// are you safari? body.safari for safari
	
if ($.browser.safari) {
    $("body").addClass("safari");
  }

//
// Are you firefox? Then no bookmark for you!
if($.browser.mozilla) {
	$("#bookmarkLink").remove();
}


// validator for clinical trials on the exclusion box
    var validator =	$("#rcToClinicalTrials").validate({
	         errorClass: "researchFormError",
            rules: {	
              ethnicity: {required:true},
			  gender:{required:true},
			  medcond: {required:false},			  
	          signupEmail: {
	                required: true,
	                email: true
	          },
	          signupEmailC: {
	                required: true,
	                equalTo: "#signupEmail",
	                email: true
	          }
            },
			messages: {
            gender: "Please choose your gender.",            
            signupEmail: "Please enter a valid email address.",
            signupEmailC: "Please enter the same email."
			},
			submitHandler: function(form) {
      			$(".thankYouFlyOut").css("display","block");
      			setWindowUnloadText();
   				form.submit();
        	}
    });


// video player and flyout w/ opacity overlay
	// to stop video player when the div closes.
        var flashVideoPlayer;
        function callCloseSWF() {
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        flashVideoPlayer = (isIE) ? window['movie'] : document['movie'];
        flashVideoPlayer.closeSWF();
    }
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
			return arrayPageSize;
		};

function logEvent(eventName) {
	logurl = "/logevent/" + eventName + "-study-0.html";		
	$.ajax({
		data:'',
		url: logurl,
		timeout: 2000,
		error: function() {
			console.log("Failed to log");
		},				
		success: function(response) {				
		}
	});		
}


var arrPageSizes = ___getPageSize();

// to open div and the opacity wrapper
function openVideoWindow() {
	logEvent("openVideoWindow/" + document.getElementById("videoWindow").getAttribute("clipid"));
	$("#videoWindow").css("display","block");
	$('#opacityWrapper').css({
				opacity:			'.7',
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();

}

function closeVideoWindow() {
	logEvent("closeVideoWindow/" + document.getElementById("videoWindow").getAttribute("clipid"));
	$('#videoWindow').fadeOut();
	$('#opacityWrapper').fadeOut();
	callCloseSWF();
}


// to open div and the opacity wrapper
function openDescriptionWindow() {
	logEvent("openDescriptionWindow/" + document.getElementById("descriptionWindow").getAttribute("studyid"));
	$("#descriptionWindow").css("display","block");
	$('#opacityWrapper').css({
				opacity:			'.7',
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
}



function closeDescriptionWindow() {
	logEvent("closeDescriptionWindow/" + document.getElementById("descriptionWindow").getAttribute("studyid"));
	$('#descriptionWindow').fadeOut();
	$('#opacityWrapper').fadeOut();
}




/*
#
#
# schedule page
#
*/


function siteListSelection() {
	$(".siteList").each(
		function(intIndex) {
			$(this).bind("click",
				function() {
			//	directions.clear();
					var lng = $(this).attr("lng");
					var lat = $(this).attr("lat");
					scheduleMap.setCenter( new GLatLng(lat, lng), 13);
				$("#gmap").css({
					width: "99.2%",
					position: "static"
				});
				$("#gpanel").css({
					display: "none"
				});
				$(".addressBar").css("visibility", "hidden");
				
				}
			
			)
		
		}	
	);
}
directionstf = false;
function showDirections() {
	$(".getDirectionsLink").each(
		function(intIndex) {
			$(this).bind("click",
				function() {
				if (directionstf == true) {
					directions.clear();
				}
			
					latLng = $(this).attr("gmaps");
					var directionsPanel = document.getElementById("gpanel");
					directions = new GDirections(scheduleMap, directionsPanel);
					directions.load("from: " + zip + " to: " + latLng );
					directionstf = true;
					$("#gmap").css({
						position: "relative",
						left: "0px"
					});
					$("#gmap").animate({
						width: "53.2%"
					}, 50);
					
					$("#gpanel").css({
						display: "block"
					});
					$("#gmap").animate({
						width: "53.2%"
					}, "slow");
					$(".addressBar").css("visibility", "visible");
					
				
				}
			
			)
		
 		}	
	);



// for the address search
$("#addressButton").click(function() {
		directions.clear();
		var changeZip = $("input#zipInput").attr("value");
		var streetAddress = $("#addressInput").attr("value");
		var directionsPanel = document.getElementById("gpanel");
		directions = new GDirections(scheduleMap, directionsPanel);
		directions.load("from: " + streetAddress + ", " + changeZip + " to: " + latLng );
		var directionstf = true;
	
	})


$("input#zipInput").attr("value", "");

}

$("#studyDescription table").removeAttr("style")



function setupContactValidation() {
    var validator =	$("#researchCenterForm").validate({
	         errorContainer:"#messageBox",
	         errorClass: "researchFormError",
	         wrapper: null,
	         errorPlacement: function(error, element) { 
	            error.insertBefore(element);
	        },
            rules: {	
                zip: {
                    required:true,
                    digits: true,
                    minlength: 5,
                    maxlength: 5
                },
                email: {
                    required: true,
                    email: true
                },
                confirmEmail: {
                    required: true,
                    equalTo: "#email",
                    email: true
                },		
                firstname: {
                    required:true
                },		
                lastname: {
                    required:true
                }
            },
            messages: {
	            firstname: "Please enter your first name.",
	            lastname: "Please enter your last name.",
	            username: {
	                required: "Please enter a username.",
	                minLength: "Your username must consist of at least 2 characters."
	            },
	            password: {
	                required: "Please provide a password.",
	                minLength: "Your password must be at least 5 characters long."
	            },
	            confirmPassword: {
	                required: "Please provide a password.",
	                minLength: "Your password must be at least 5 characters long.",
	                equalTo: "Please enter the same password as above."
	            },
	            email: "Please enter a valid email address.",
	            confirmEmail: "Please enter the same email.",
	            zip: "Please enter a valid zip code."
            },
	        success: function(label){
	            // set   as text for IE 
	            label.html(" ").addClass("valid");
			},
			submitHandler: function(form) {
      			setWindowUnloadText();
   				form.submit();
        	}
		});
}	