var maxTextareaLength = 1000;

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

function isEmail(email) {
	var filter = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	var result = filter.test(email);
	return (result != false);
}

function forceMaxLength(){
  var maxLength = parseInt(this.getAttribute('maxlength'));
  if(this.value.length > maxlength){
   this.value = this.value.substring(0,maxlength);
  }
 }

function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
   		obj.addEventListener(evType, fn, false); 
   		return true; 
 	} else if (obj.attachEvent){ 
   		var r = obj.attachEvent("on"+evType, fn); 
   		return r; 
 	} else { 
   		return false; 
 	} 
}	

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

function openInImageWindow(e) {
	var event;
	if (!e) event = window.event;
	else event = e;
	// Abort if a modifier key is pressed
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
		return true;
	}
	else {
		// Change "_blank" to something like "newWindow" to load all links in the same new window
	    //var newWindow = window.open(this.getAttribute('href'), '_blank');
	    
	    var tempClassName = this.className;
	    var tempClassNameArray = tempClassName.split("-");
	    var WinProps;
	    var h = 0;	    
			tempClassNameArray[2] = tempClassNameArray[2].replace(/ /i,"");			
			
			h=0+(tempClassNameArray[2]*1)+25;			
			picgif=this.getAttribute("href");
			
			WinProps="width="+tempClassNameArray[1]+",height="+h+",location=no,status=no,directories=no,toolbar=no,scrollbars=yes,menubar=no,resize=no,top=50,left=50";
			var newWindow = window.open("","Diatribe",config=WinProps);
			newWindow.document.write("<HTML>");
			newWindow.document.write("<HEAD><TITLE>Display Image</TITLE></HEAD>");
			newWindow.document.write("<BODY>");
			newWindow.document.write("<CENTER><span style='font-family:arial;font-size:12px;'><A HREF='#' onClick='self.close()'>Close</A></span><br><IMG SRC="+picgif+" BORDER='0' HSPACE=0 VSPACE=0><BR>");
			newWindow.document.write("<span style='font-family:arial;font-size:12px;'><A HREF='#' onClick='self.close()'>Close</A></span></CENTER>");
			newWindow.document.write("</BODY>");
			newWindow.document.write("</HTML>");
			newWindow.document.close();		
		
		if (newWindow) {
			if (newWindow.focus) {
				newWindow.focus();
			}
			return false;
		}
		return true;
	}
}	

function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Change this to the text you want to use to alert the user that a new window will be opened
		var strNewWindowAlert = " (opens in a new window)";
		// Find all links
		var links = document.getElementsByTagName('a');
		var objWarningText;
		var link;
		for (var i = 0; i < links.length; i++) {
			link = links[i];			
			if (/\bexternal/.test(link.className)) {				
				link.onclick = openInExtWindow;					
			}else if (/\bregistration/.test(link.className)) {				
				link.onclick = openInRegWindow;					
			}else if (/\bflash/.test(link.className)) {
				link.onclick = openInFlashWindow;		
			}else if (/\bimage/.test(link.className)) {
				link.onclick = openInImageWindow;								
			}else if (/\bprintview/.test(link.className)) {
				link.onclick = openInPrintWindow;					
			}
		}
		objWarningText = null;
	}
}

addEvent(window, 'load', getNewWindowLinks);

function isRadioOrCheckbox(formElement){
	if (/\bradio/.test(formElement.className) || /\bcheckbox/.test(formElement.className)) {	
		return true;	
	}else{
		return false;	
	}
}

function validateForm(e){
	theForm = document.getElementById("signup");
	// Check that the browser is DOM compliant	
	if (document.getElementById && document.createElement && document.appendChild) {
	
		var formInputs = document.getElementsByTagName('input');
		var formSelects = document.getElementsByTagName('select');
		var formTextareas = document.getElementsByTagName('textarea');
		
		var validateErrorMsg="";
		var validateObjectFocus;
		var formElement;
		var failedValidation;
		var radioElement = "";
		var	radioChecked = false;
		var otherElement = "";
		
		for (var i = 0; i < formInputs.length; i++) {	
			failedValidation = false;
			formElement = formInputs[i];
			
			// Find all elements with a class name of "required"
			if (/required\b/.test(formElement.className)) {	
				// Create an em element containing the new window warning text and insert it after the link text
				
				if(isRadioOrCheckbox(formElement) && (radioElement.name == formElement.name || radioElement == "")) {
					if(radioElement == ""){
						radioElement = formElement;
					}
					if(formElement.checked){
						radioChecked = true;
						if(formElement.value == "Other"){
							otherElement = formElement.name.replace("[]","")+"other";								
						}	
					}
				}else if (radioElement != ""){					
					if(!radioChecked || (otherElement != "" && trim(document.getElementById(otherElement).value)=="")){
						failedValidation = true;
						if(validateErrorMsg == ""){
							validateObjectFocus = radioElement;	
						}
						validateErrorMsg = validateErrorMsg + "\"" + radioElement.title + "\"" + " is required\n";							
					}
					if(isRadioOrCheckbox(formElement)){
						radioElement = formElement;
						if(formElement.checked){
							radioChecked = true;	
						}else{
							radioChecked = false;	
						}
					}else{
						radioElement = "";
						radioChecked = false;
						if(trim(formElement.value)==""){
							failedValidation = true;
							if(validateErrorMsg == ""){
								validateObjectFocus = formElement;	
							}
							validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " is required\n";							
						}
					}
				}else{					
					radioElement = "";
					radioChecked = false;
					if(trim(formElement.value)==""){
						failedValidation = true;
						if(validateErrorMsg == ""){
							validateObjectFocus = formElement;	
						}
						validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " is required\n";							
					}
				}				
			}
			if (!failedValidation) {					
				if(formElement.name=="email"){					
					if(!isEmail(formElement.value)){												
						failedValidation = true;
						if(validateErrorMsg == ""){
							validateObjectFocus = formElement;
						}
						validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " is not valid\n";							
					}	
				}
			}
			if (!failedValidation){
				if(formElement.name=="emailconfirm"){
					if(formElement.value != document.getElementById("email").value){
						failedValidation = true;
						if(validateErrorMsg == ""){
							validateObjectFocus = formElement;
						}
						validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " doesn't match the \"Email\" you entered\n";							
					}	
				}	
			}
		}
		
		for (var i = 0; i < formSelects.length; i++) {	
			failedValidation = false;
			formElement = formSelects[i];
			// Find all elements with a class name of "required"
			if (/required\b/.test(formElement.className)) {	
				// Create an em element containing the new window warning text and insert it after the link text
				if(trim(formElement.value)==""){
					failedValidation = true;
					if(validateErrorMsg == ""){
						validateObjectFocus = formElement;	
					}
					validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " is required\n";							
				}
			}
		}
		
		for (var i = 0; i < formTextareas.length; i++) {	
			failedValidation = false;
			formElement = formTextareas[i];
			// Find all elements with a class name of "required"
			if (/required\b/.test(formElement.className)) {	
				// Create an em element containing the new window warning text and insert it after the link text
				if(trim(formElement.value)==""){
					failedValidation = true;
					if(validateErrorMsg == ""){
						validateObjectFocus = formElement;	
					}
					validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " is required\n";							
				}
			}
			if(!failedValidation){
				if(formElement.value.length > maxTextareaLength){
					failedValidation=true;
					if(validateErrorMsg == ""){
						validateObjectFocus = formElement;	
					}
   					formElement.value = formElement.value.substring(0,maxTextareaLength);
   					validateErrorMsg = validateErrorMsg + "\"" + formElement.title + "\"" + " cannot exceed " + maxTextareaLength + " characters\n";
   				}  			
			}
		}
		
		if(validateErrorMsg==""){
			theForm.submit();
		}else{
			validateObjectFocus.focus();
			alert(validateErrorMsg);
			return false;	
		}
	}
}

function attachFormValidation(){
	if(document.getElementById("signup")){
		document.getElementById("signup").onsubmit = validateForm;
	}
}

addEvent(window, "load", attachFormValidation);		

function addSubscribeBlock(){
	if(window.location.href.indexOf(".php")>0 && window.location.href.indexOf("home.php")<=0){
		var divMain = document.getElementById("main");
		if(divMain){
			var mainHeadings = divMain.getElementsByTagName("h1");
			if(mainHeadings && mainHeadings.length>0){
				var mainHeading = mainHeadings[0];
				var divSub = document.createElement("div");
				divSub.className="callout-right";
				var divSubP = document.createElement("p");
				divSubP.appendChild(document.createTextNode("Why not subscribe for free to diaTribe? Receive the latest information from the cutting edge of diabetes research and product innovation. "));
				divSub.appendChild(divSubP);
				var divSubA = document.createElement("a");
				divSubA.setAttribute("href", "/subscribe.php");
				divSubA.appendChild(document.createTextNode("Subscribe here"));
				divSubP.appendChild(divSubA);
				mainHeading.parentNode.insertBefore(divSub, mainHeading.nextSibling);				
			}
		}
	}
}

addEvent(window, "load", addSubscribeBlock);