MAT = window.MAT || {};
MAT.USC = window.MAT.USC || {};

MAT.USC.Global = function() {
	function _init() {
		jQuery('form.validate').live('submit', function() {
			if (MAT.USC.Global.validate_form(this)) {
				// set up field dependencies
				if (jQuery('#00N80000002UJr8').val() != 'MAT') {
					jQuery('#00N80000003aB3Y').val('TESOL');
				} else {
					jQuery('#00N80000003aB3Y').val('');
				}

				return true;
			}
			
			return false;
		});
	
	}
	
	function _validate_form(the_form) {
		var error = false;
		var label, children;
		var label_val = '';
		
		// check required & validate fields
		jQuery(the_form).find('input.validate,textarea.validate,input.required,textarea.required,select.required').each(function() {
			// clone the label, remove it's children, to get the actual label text
			label = jQuery(this).prev('label').clone();
			children = jQuery(label).children();
			label.children().remove();
			label_val = (jQuery(label).text() != '') ? " for '" + jQuery(label).text() + "'" : '';
			
			// check required
			if (jQuery(this).hasClass('required')) {
				if (jQuery(this).val() == '') {
					alert("You must supply a value" + label_val + ".");
				
					jQuery(this).focus();
					jQuery(this).addClass('error');
					error = true;
					return false;
				} else {
					jQuery(this).removeClass('error');
				}
			} // end required class check
		});
		
		if (error) {
			return false;
		} else {
			return true;
		}
	}
	
	return {
		init: function() {
			_init();
		},
		
		validate_form: function(form) {
			return _validate_form(form);
		},
		
		close_modal: function() {
			jQuery.closeDOMWindow();
		}
	};
}();

//makes select boxes custom style-able
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "300";


/* select box script */

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				if(!inputs[a].getAttribute("disabled")) {
					span[a].onmousedown = Custom.pushed;
					span[a].onmouseup = Custom.check;
				} else {
					span[a].className = span[a].className += " disabled";
				}
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				if(!inputs[a].getAttribute("disabled")) {
					inputs[a].onchange = Custom.choose;
				} else {
					inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
				}
			}
		}
		document.onmouseup = Custom.clear;
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;
//END SELECT BOX SCRIPT

jQuery(document).ready(function() {
	MAT.USC.Global.init();
	
	//start up superfish menu
	jQuery('ul.sf-menu').supersubs({ 
	            minWidth:    12,   // minimum width of sub-menus in em units 
	            maxWidth:    27,   // maximum width of sub-menus in em units 
	            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
	                               // due to slight rounding differences and font-family 
	        }).superfish({ 
		delay:      0,                            // one second delay on mouseout 
		animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation 
		speed:       'fast',                          // faster animation speed 
		autoArrows:  true,                           // disable generation of arrow mark-up 
		dropShadows: true                           
	});
	
	//config DOMwindow button 1				
	jQuery('.reqinf').openDOMWindow({ 
		eventType:'click', 
		width: 465,
		height: 580,
		borderSize:'0',
		windowPadding:0,
		windowBGColor:'transparent'

	});
	
	//config DOMwindow button 2
	jQuery('.reqinf2').openDOMWindow({ 
		eventType:'click', 
		width: 465,
		height: 580,
		borderSize:'0',
		windowPadding:0,
		windowBGColor:'transparent'

	});
	
	//config DOMwindow button 3
	jQuery('.reqinf_sharebox').openDOMWindow({ 
		eventType:'click', 
		width: 465,
		height: 580,
		borderSize:'0',
		windowPadding:0,
		windowBGColor:'transparent'

	});
	
	//if this is the homepage, execute this javascript
	if (jQuery('body').hasClass('home') == true){
		/*
	    Start up Nivo Slider.
	    See: http://nivo.dev7studios.com/
	  	*/
		$('#homepage-slider').nivoSlider({
	    effect          : 'fade',
	    directionNav    : false,
	    captionOpacity  : 1,
	    animSpeed       : 300,
	    manualAdvance   : false,
		directionNav: true,
		directionNavHide: false,
	    pauseTime       :3000,
	    afterLoad       : function() {

	      var $sliderCaptions = $('.slider-caption'),
	          $controlItems   = $('.nivo-control');

			$('.nivo-controlNav').prepend('<span href="#" id="customPrev"></span>');
			$('.nivo-controlNav').append('<span href="#" id="customNext"></span>');

			$("#customPrev").click(function () {
				$("a.nivo-prevNav").trigger('click');
			});

			$("#customNext").click(function () {
				$("a.nivo-nextNav").trigger('click');
			});

	    } // afterLoad


	  });	
	  
    // jQuery(".slidetabs").tabs(".featimages > div", {
    // 
    //          // enable "cross-fading" effect
    //          effect: 'fade',
    //          fadeOutSpeed: "slow",
    // 
    //          // start from the beginning after the last tab
    //          rotate: true
    // 
    //          // use the slideshow plugin. It accepts its own configuration
    //        }).slideshow({
    //          autoplay: true,
    //          interval:5000,
    //          clickable:false});
    // 
           jQuery('#slidedeckpageswrapper').fadeIn('slow');
         jQuery('#home_reqinf').slideToggle('slow');
	}
	
	//any page other than home
	else {
		
		//if this is the map page, then load pins
		if (jQuery('body').hasClass('mapPage') == true) {
			jQuery(".pin").tooltip({ effect: 'slide', relative: true, position: 'bottom left', offset: [-100,16]});
			jQuery('#map a.reqinf').fadeIn('fast');	
			jQuery("#map").children(".pin").hide().fadeInSequence(100);
		}
		
		//for interior pages, makes select option in sidebar go directly to that URL		
		jQuery('select.styled').change(function(){
			location=document.current.theme.options[document.current.theme.selectedIndex].value;
		});
		
		//fade in and set up the floating sidebar, or "sharebox"
		jQuery('#shareboxwrapper').fadeIn('fast');
		var msie6 = jQuery.browser == 'msie' && jQuery.browser.version < 7;

		if (!msie6) {
			var top = jQuery('#sharebox').offset().top - parseFloat(jQuery('#sharebox').css('margin-top').replace(/auto/, 0));
		    
			jQuery(window).scroll(function (event) {
		    	// what the y position of the scroll is
		    	var y = jQuery(this).scrollTop();

		    	// whether that's below the form
		    	if (y >= top) {
			
		        // if so, add the fixed class
		        jQuery('#sharebox').addClass('fixed');
		
		      	} else {
			
		        // otherwise remove it
		        jQuery('#sharebox').removeClass('fixed');
		    	}
		  	});
		}
		
		//configure commentbox scripts for expandable course descriptions
		jQuery('#commentbox').hide();

		jQuery('a.comment').click(function() {
		 var id = $(this).attr('id');
		 jQuery('#commentbox' + id).slideToggle(500);
		 // alert(id);
		 return false;
		 });
	}
	//3 step organic lead form styles and validation
	jQuery('#step1 .next').click(function(event) {
		event.preventDefault();
		
	  	jQuery('#step1').fadeOut('slow', function() {
	  	jQuery('#step2').fadeIn('fast');

	  });
	});
	
	//3 step organic lead form styles and validation STEP 2
	jQuery('#step2 .next-2').click(function(event) {
	  	event.preventDefault();
		var ok = true;

		if(jQuery('#education2').val() == '') {
			alert('Please select your highest level of education');
			jQuery('#education2').focus();
			ok = false;
		}
		if(ok) {
			if(jQuery('#gpaRange').val() == '') {
				alert('Please select your undergraduate GPA range');
				jQuery('#gpaRange').focus();
				ok = false;
			} 
		}
		if(ok) {
			if(jQuery('#programinterest2').val() == '') {
				alert('Please select your program of interest');
				jQuery('#programinterest2').focus();
				ok = false;
			} 
		}
	    if(ok) {
	    	if(jQuery('#concentrationinterest2').val() == '') {
	    		alert('Please select your concentration of interest');
	    		jQuery('#concentrationinterest2').focus();
	    		ok = false;
	    	} 
	    }
		if (ok){
				jQuery('#step2').fadeOut('slow', function() {
			  	jQuery('#step3').fadeIn('slow');
			  });
		}

	});

	//3 step organic lead form styles and validation SUBMIT
	jQuery('#submit').click(function() {
	  	var ok = true;

		if (jQuery('#first_name').val() == '') {
			alert('Please enter your first name.');
			jQuery('#first_name').focus();
			return false;
		}

		if (jQuery('#last_name').val() == '') {
			alert('Please enter your last name.');
			jQuery('#last_name').focus();
			return false;
		}

		if (jQuery('#emailfield').val() == '') {
			alert('Please enter your email address.');
			jQuery('#emailfield').focus();
			return false;
		}

		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		if (!pattern.test(jQuery('#emailfield').val().toLowerCase())) {
			alert('Please enter a valid email address.');
			jQuery('#emailfield').focus();
			return false;
		}

		if (jQuery('#phone2').val() == '') {
			alert('Please enter your phone number.');
			jQuery('#phone2').focus();
			return false;
		}

		if (jQuery('#zip').val() == '') {
			alert('Please enter your zip code (postal code).');
			jQuery('#zip').focus();
			return false;
		}

		if (jQuery('#state2').val() == '') {
			alert('Please select your state.');
			jQuery('#state2').focus();
			return false;
		}
		if (jQuery('#country').val() == '') {
			alert('Please select your country.');
			jQuery('#country').focus();
			return false;
		}

	});
	
	//on country change, automatically fill in country code in phone field
	$('#country').change(function(){
		$('#phone2').val($(this).find('option:selected').attr('title'));
		$('#phone2').focus();
	});
});
