(function(){

    //Create Namespace
    if (!window.EMS) {
        window['EMS'] = {}
    }
    
    //Helper function to check if an element (i.e. div) exists. Argument is element id
    var exists = function(element){
        if (!document.getElementById(element)) {
            return false;
        } else {
            return true;
        }
    }
    window['EMS']['exists'] = exists;
    
    // Dropdown Navigation
    var navigation = function(){
    
        $('#navigation dd').each(function(){
        
            $(this).hover(function(){
            
                $(this).find('ul.level1:hidden').slideDown('normal');
                $(this).find('a.level0').addClass('active');
                
            }, function(){
            
                $(this).find('ul.level1:visible').slideUp('normal');
                $(this).find('a.level0').removeClass('active');
            });
            
        });
        
    }
    window['EMS']['navigation'] = navigation;
    
    // image rotator function
    var imageRotator = function(){
    
        //Show first image in case .first class is not applied
        $('#imageHolder img:eq(0)').show();
        
        // rotate images when buttons are clicked
        $('#imageButtons li').each(function(){
        
            var myIndex = $('#imageButtons li').index(this);
            
            // $(this).find('a').click(function() {
            
            $(this).click(function(){
            
                $(this).find('a').click(function(){
                    return false;
                });
                // show corresponding image
                $('#imageHolder img:eq(' + myIndex + ')').show();
				
				// show corresponding caption
				$('#imageCaptions span:eq(' + myIndex + ')').removeClass("hide");
				
				// hide other captions
				$('#imageCaptions span:not(:eq(' + myIndex + '))').addClass("hide");
                
                // hide other images
                $('#imageHolder img:not(:eq(' + myIndex + '))').hide();
                
                // replace markup in buttons
                var currentIndex = $('#imageButtons li.current').text();
                $('#imageButtons li.current').html('<a href="#">' + currentIndex + '</a>');
                $('#imageButtons li.current').removeClass('current');
                
                $(this).addClass('current');
                $(this).html(myIndex + 1);
                
                return false;
                
            });// /end click
        });
        
        function clickButton(element, index){
            $(element).click(function(){
                //show corresponding image
                $('#imageHolder img:eq(' + index + ')').show();
                
                // hide other images
                $('#imageHolder img:not(:eq(' + index + '))').hide();
                
				//show corresponding caption
                $('#imageCaption span:eq(' + index + ')').show();
                
                // hide other captions
                $('#imageCaption span:not(:eq(' + index + '))').hide();
				
                // replace markup in buttons
                var currentIndex = $('#imageButtons li.current').text();
                $('#imageButtons li.current').html('<a href="#">' + currentIndex + '</a>');
                var newButton = $('#imageButtons li.current a');
                clickButton(newButton, currentIndex - 1);
                $('#imageButtons li.current').removeClass('current');
                
                $(this).parent('li').addClass('current');
                $(this).parent('li').html(index + 1);
                
                return false;
            });
        }
    }
    window['EMS']['imageRotator'] = imageRotator;
    
    var contactForm = function(){
   
        var myRules = jQuery.validationAide.getDefaultValidationRules();
        myRules.add('validator-verify-email', 'Emails do not match', function(fieldValue, fieldObj){
            if (fieldValue != $('#email').val()) {
                return false;
            }
            return true;
        });
        
        myRules.add('validator-verify-multiple', 'Please select at least one solution area of interest to you.', function(fieldValue, fieldObj){
            test = 1;
            return true;
        });
        
        
        $("#contactForm").validationAideEnable(myRules, {
            summaryFieldMessageFormat: '##FIELD##'
        });
        
        //Create a masked input for zip codes
      /*  $("#zip").mask("9999999999", {
            placeholder: ""
        });*/
        
        //Setup country drop-down select code (toggles between a field / drop down for state, depending on country selected)
        $("#country").bind("change", function(e){
            var value = this.options[this.selectedIndex].value;
            var stateObj = $('#state')[0];
            var hiddenStateObj = $('#state-hidden')[0];
            if (value == "Canada" || value == "United States of America" || value == "") {
                if (stateObj.type == "text") {
                    stateObj.id = "state-hidden";
                    hiddenStateObj.id = "state";
                    $('#stateLabel')[0].innerHTML = "State / Province:";
                }
            } else {
                if (stateObj.type != "text") {
                    stateObj.id = "state-hidden";
                    hiddenStateObj.id = "state";
                    $('#stateLabel')[0].innerHTML = "State / Province / Country:";
                }
            }
            
        });
        
        //Setup the interestSolutions checkbox to store a concatenated list of selected items on click.
        //used to validate that at least one item is clicked.
        $("input[name='interestSolution']").bind("click", function(e){
        	var interestList = $('#interestSolutionList')[0];
			if (interestList) {
				interestList.value = "";
			}
            $("input[name='interestSolution']").each(function(i){
                var interestList = $('#interestSolutionList')[0];
                if (interestList) {
                    var currentList = interestList.value;
                    var currentValue = this.value;
                    if (this.checked) {
                        if (!currentList || currentList == "") {
                            interestList.value = currentValue;
                        } else if (currentList.indexOf(currentValue) < 0) {
                            interestList.value += "," + currentValue;
                        }
                    } 
                }
            });
            
        });
        
    }
    window['EMS']['contactForm'] = contactForm;
    
    //Function to enable Related Videos to load into Video Player
    var loadVideo = function() {
    	
    	//path to the folder with the flv files (in this case it is relative to flvplayer folder)
    	var contentPath = "../../media";
    	//path to flv player
    	var playerPath = "flash/flvplayer/flvplayer.swf";
    	
    	$('#videoList li a').each(function() { 
    		
    		//Get title and description
    		var myTitle = $(this).find('span.title').text();
    		var myDesc = $(this).find('span.description').html();
    		
    		//Video file name
    		var fileName = $(this).attr('href');
    		
    		$(this).click(function() {
    			
    			//Load title and description of video 
    			$('#mainContent h2:eq(0)').text(myTitle);
    			$('#videoDescription').html(myDesc);
    			
    			//load video in player
    			playVideo(fileName, playerPath, contentPath);
    			
    			return false;
    		}); //end click
    	});
    	
    	function playVideo(video, playerPath, contentPath) {
    		var params = {};
    		params.scale = "noscale";
    		params.allowfullscreen = "false";
    		params.salign = "tl";
    		params.base = ".";
    		params.wmode = "transparent";
    		
    		var flashvars = {};
    		flashvars.playerpath = "";
    		flashvars.contentpath = contentPath;
    		flashvars.video = video;
    		//uncomment and type in skin name if using a specific skin
    		flashvars.skin = "SkinUnderPlayStopSeekMuteVol.swf";
    		flashvars.skincolor = "0xE4E1E4";
    		flashvars.skinscalemaximum = "1";
    		flashvars.autoplay = "true";
    		
    		var attributes = {};
    		
    		swfobject.embedSWF(playerPath, "videoPlayer", "360", "300", "9.0.0", "flash/expressInstall.swf", flashvars, params, attributes);
    	}
    	
    }
    window['EMS']['loadVideo'] = loadVideo;
})();

// All functions that need to be executed after page load go here
$(document).ready(function(){

    EMS.navigation();
    
    // if page has 'imgeRotator', activate functionality
    if (EMS.exists('imageRotator')) {
        EMS.imageRotator();
    }
    
    //If the page is the contact us form
    if (EMS.exists('contactForm')) {
        EMS.contactForm();
    }
    
    //If page is video page, load function for related videos
    if (EMS.exists('videosBox')) {
    	EMS.loadVideo();
    }
});

function searchOnEnter (field, evt) {
    var keyCode = document.layers ? evt.which : document.all ?
    evt.keyCode : evt.keyCode;
    if (keyCode != 13 && keyCode !=9)
        return true;
    else {
        document.location.href= "http://www.ems-t.com/search/search.aspx?searchtext=" + field.value
        return false;
        }
 }
