// site.js
var ASD = {};

ASD.fireEvent = function(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
};

ASD.generateFormErrorTooltips = function()
{
    // slice and dice form error messages
    var elementsFormError = $$('.formError');
    if (elementsFormError)
    {
        elementsFormError.each(function(item)
        {
        	var field = item.up(".field");
        	if(!field || field == undefined) {
        		field = item.up("div").previous(".field");
        	}
        	var errorTrigger = field.down(".errorTrigger");
            try
            {
                errorTrigger.title = item.firstChild.nodeValue;
                new Tooltip(errorTrigger, {
                    appearDuration: .1,
                    backgroundColor: '#ffffbb',
                    borderColor: '#ffcc66',
                    delay: 100,
                    hideDuration: .1,
                    maxWidth: 250,
                    mouseFollow: false,
                    opacity: .95,
                    textColor: '#000000'
                });
                errorTrigger.setStyle( {
                	visibility:'visible'
                	});
            }
            catch (e)
            {
            	if(errorTrigger && errorTrigger != undefined) {
	                errorTrigger.setStyle( {
	                	visibility:'visible'
	                	});
            	}
            }
        });
    }
};

ASD.Window = {
    open: function(inOptions)
    {
        this.options = {
            url: 'javascript:void(0)',
            width: 600,
            height: 500,
            name:"_blank",
            location:"no",
            menubar:"no",
            toolbar:"no",
            status:"yes",
            scrollbars:"yes",
            resizable:"yes",
            left:"",
            top:"",
            normal:false
        };
        Object.extend(this.options, inOptions || {});

        if (this.options.normal)
        {
            this.options.menubar = "yes";
            this.options.status = "yes";
            this.options.toolbar = "yes";
            this.options.location = "yes";
        }

        this.options.width = this.options.width < screen.availWidth ? this.options.width : screen.availWidth;
        this.options.height = this.options.height < screen.availHeight ? this.options.height : screen.availHeight;
        var openoptions = 'width=' + this.options.width + ',height=' + this.options.height + ',location=' + this.options.location + ',menubar=' + this.options.menubar + ',toolbar=' + this.options.toolbar + ',scrollbars=' + this.options.scrollbars + ',resizable=' + this.options.resizable + ',status=' + this.options.status;
        if (this.options.top !== "")
        {
            openoptions += ",top=" + this.options.top;
        }
        if (this.options.left !== "")
        {
            openoptions += ",left=" + this.options.left;
        }
        window.open(this.options.url, this.options.name, openoptions);
        return false;
    }
}; // end of ASD.Window


/**
 *    when using removeTextboxText, set the initial/default text of the input before calling
 */
ASD.removeTextboxText = function(elemId)
{
    if ($(elemId) && $(elemId).value === $(elemId).initText)
    {
        $(elemId).value = "";
    }
};

ASD.setTextboxText = function (elemId)
{
    if ($(elemId) && $(elemId).value === "")
    {
        $(elemId).value = $(elemId).initText;
    }
};

ASD.prepareTextFieldWithInfoTextToSubmit = function(textBoxId)
{
    if ($(textBoxId) && $(textBoxId).value == $(textBoxId).initText)
    {
        ASD.removeTextboxText(textBoxId);
    }
};

ASD.setupSearchForSchoolForm = function()
{
    var formButton = $('find-form-header-submit');
    if ( formButton )
    {
        Event.observe(formButton, 'click', function(event)
        {
            Event.stop(event);
            var value = $('stateProvince-header').getValue().escapeHTML();
            $('stateProvince-header').setValue(value);
            var form = $('find-form-header').submit();
        });
    }
};

ASD.submitSubscribeWidget = function (subscribeSubmitButton, suffix)
{
    var page = $F('subscribe_source_page-' + suffix);
    var site = $F('subscribe_source_site-' + suffix);
    var email = $F('subscribe_email-' + suffix);
    var toURL = "/subscribe/" + escape(email) + "/" + escape(site) + "/" + escape(page);

    ASD.Window.open({
        url:toURL,
        width:520,
        height:350
    });
};

ASD.setZebraStripes = function()
{
    var evens = $$('.table-zebra tr:nth-child(odd)');
    if (evens)
    {
        evens.each(function(tr)
        {
            tr.addClassName('zebra-fill');
        });
    }
};

ASD.getControllerPath = function()
{
    var controllerPath = "";
    var currUrl = window.location.href;
    var segments = currUrl.split("/");
    if (segments.size() >= 3)
    {
        controllerPath = segments[3]; //http, blank, domain, controllerPath
    }
    return controllerPath;
};

ASD.getPathToHighlight = function(deg, spec)
{
    var urlPath = "";
    var urlPrefix = ASD.getControllerPath(); // substring first / after ://, to next / (context root)
    if (urlPrefix != "")
    {
        if (!deg.empty() && !spec.empty())
        {
            // both exist
            urlPath = "/" + urlPrefix + "/" + deg + "/" + spec;
        } else if (!spec.empty())
        {
            // only specialization
            urlPath = "/" + urlPrefix + "/all-degrees/" + spec;
        } else if (!deg.empty())
        {
            // only degree
            urlPath = "/" + urlPrefix + "/" + deg;
        }
    }
    return urlPath;
};

ASD.setHighlightLeftNav = function()
{
    // implemented in featured and faqs JavaScript files
};

ASD.setSpecializationDropdown = function()
{
    // implement in featured.js
};

ASD.expandLeftNavForShortBody = function()
{
    // left-hand nav: expand body to height of left-hand nav
    var mainBody = $$('.asd-main')[0];
    var leftNav = $('left-nav-id');
    if (mainBody && leftNav)
    {
        var mainHeight = mainBody.getHeight();
        var leftNavHeight = leftNav.getHeight();
        if (leftNavHeight > mainHeight)
        {
            mainBody.style.height = leftNavHeight + "px";
        }
    } // end if main body
};

ASD.setAnchorToExternalToPopNewWindow = function()
{
    // markup validation-compliant solution for target <a> attribute
    // handle multiple campus Request Information content toggle
    var elements = Element.select($(document), "a.external");
    var element;//, id, toggler;
    elements.each(function(item)
    {
        Event.observe(item, 'click', function(event)
        {
        	if(item.href.indexOf("privacy-policy")>-1){
        		windowWidth=1000;
        	}else{
        		windowWidth=700;
        	}
            ASD.Window.open({
                url: item.href,
                width: windowWidth
            });
            Event.stop(event);
        });
    });
};

/**
 * Sets up the fancy make-blank-on-click for textboxes. It captures the original
 * text so we can replace it if they leave it blank.
 */
ASD.setupTextBoxForClickReplacement = function(textElementID, submitElementID, defaultText)
{
    var textbox = $(textElementID);
    if (textbox)
    {
        textbox.initText = defaultText;

        textbox.observe('focus', function(event)
        {
            ASD.removeTextboxText(textbox);
        });

        textbox.observe('blur', function(event)
        {
            ASD.setTextboxText(textbox);
        });

        if ($(submitElementID))
        {
            /* bind to mousedown so other events can listen in on click.
               This has to happen before other click events fire */
            $(submitElementID).observe('mousedown', function(event)
            {
                ASD.prepareTextFieldWithInfoTextToSubmit(textbox);
            });
        }
    }
};

ASD.setupOnClickToClearBoxAndCookieForSearch = function(textElementID, submitElementID)
{
    if($(textElementID)){
    	$(textElementID).observe('focus', function(event){
    		if($F(textElementID) == "Enter a zip or state" || $F(textElementID) == "State/ZIP"){        
    			$(textElementID).value = '';
    		}
    	});
    }
    
    if($(submitElementID)){
    	$(submitElementID).observe('mousedown', function(event){
    		if($F(textElementID) == "Enter a zip or state" || $F(textElementID) == "State/ZIP"){        
    			$(textElementID).value = '';
    		}
    	
    		if($F(textElementID) == ''){
    			deleteCookie("cookie_location", "/");
    		}
    	});
    }
};


ASD.setupOnSubmitToClearBoxAndCookieForSearch = function(formID, textElementID, submitElementID)
{
    if($(formID)){
    	$(formID).observe('submit', function(event){
    		if($F(textElementID) == "Enter a zip or state" || $F(textElementID) == "State/ZIP"){        
    			$(textElementID).value = '';
    		}
    	
    		if($F(textElementID) == ''){
    			deleteCookie("cookie_location", "/");
    		}
    	});
    }
};




ASD.setupHoverButtons = function()
{
    var hoverLinks = $$('.hover-button');
    if (hoverLinks)
    {
        hoverLinks.each(function(each)
        {
            Event.observe(each, 'mouseover', function(event)
            {
                var image = each.down();
                if (!image)
                    image = each;
                image.src = image.src.replace("-btn", "-btn-on");
            });
            Event.observe(each, 'mouseout', function(event)
            {
                var image = each.down();
                if (!image)
                    image = each;
                image.src = image.src.replace("-btn-on", "-btn");
            });
        });
    }
};

ASD.setupHoverSubmitButton = function()
{
    var hoverLinks = $$('.submit');
    if (hoverLinks)
    {
        hoverLinks.each(function(each)
        {
            Event.observe(each, 'mouseover', function(event)
            {
                each.addClassName('over');
            });
            Event.observe(each, 'mouseout', function(event)
            {
                each.removeClassName('over');
            });
        });
    }
};

ASD.activetab=function(){
	if($('program-information-tab')){
		Event.observe('program-information-tab', 'click', function(){
			$('tabbedSection').className="program-information-active";
		});
	}
	if($('career-information-tab')){
		Event.observe('career-information-tab', 'click', function(){
			$('tabbedSection').className="career-information-active";;
		});
	}
};


ASD.fillLocationSearchBoxes=function(){
	if(getCookie("cookie_location")){
		if($('stateProvince-header')){
			$('stateProvince-header').value=unescape(getCookie("cookie_location"));
		}
		if($('zipfilterLocation')){
			$('zipfilterLocation').value=unescape(getCookie("cookie_location"));
		}
		if($('locationInput')){
			$('locationInput').value=unescape(getCookie("cookie_location"));
		}
	}
}


ASD.respondToClick=function(event) {
	linkvalues = this.href.split(".com/");
	degreevalues=linkvalues[1].split("/");
	var list =$$('select.specialization-dropdown');
	listBox=list[0];
	for(x=0; x<listBox.options.length; x++){
		if(listBox.options[x].value==linkvalues[1] || degreevalues[0]+"/"+listBox.options[x].value==linkvalues[1]){
			listBox.options[x].selected=true;
			if($F('stateProvince-header')=="Enter a zip or state" || $F('stateProvince-header')=="State / ZIP" || $F('stateProvince-header')=="State/ZIP"){
				$F('stateProvince-header')="";
			}
			$('find-form-header').submit();
		}
	}
	event.stop();
}







function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function gup(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if(results == null)
    return "";
  else
    return results[1];
}    

document.observe("dom:loaded", function(){
    // highlight left nav for any implementing page
    ASD.setHighlightLeftNav();
    ASD.setSpecializationDropdown();
    // set zebra stripes on tables
    ASD.setZebraStripes();

    ASD.activetab();
    
    ASD.setupOnClickToClearBoxAndCookieForSearch('stateProvince-header', 'find-form-header-submit');
    ASD.setupOnClickToClearBoxAndCookieForSearch('zipfilterLocation', 'zipfilterSubmit');
    ASD.setupOnClickToClearBoxAndCookieForSearch('locationInput', 'searchButton');
    
    ASD.setupOnSubmitToClearBoxAndCookieForSearch('find-form-header','stateProvince-header', 'find-form-header-submit');
    ASD.setupOnSubmitToClearBoxAndCookieForSearch('zipfilterForm','zipfilterLocation', 'zipfilterSubmit');
    ASD.setupOnSubmitToClearBoxAndCookieForSearch('findForm','locationInput', 'searchButton');
    
    if(gup("search")){
    	if(gup("search")!="Enter a zip or state" && gup("search")!="Enter%2520a%2520zip%2520or%2520state"){
    		cookie_location=gup("search");
    		setCookie("cookie_location",cookie_location,30,"/");
    	}else{
    		deleteCookie("cookie_location", "/");
    	}
    }
    	
    ASD.fillLocationSearchBoxes();
    
    // setup button catcher for onclick
    ASD.setupSearchForSchoolForm();

    // Subscribe Footer Submit button
    ASD.setupHoverButtons();
    // setup hovers for submit buttons
    ASD.setupHoverSubmitButton();
    /*
     Impl:  Each field has a suffix added to the end becasue ID's can be duplicated
     subscribe_email-<suffix> (for all elements)
     */
    ['subscribe_submit-footer','subscribe_submit-widget'].each(function(id)
    {
        if ($(id))
        {
            var fields = id.split('-');
            if (!fields)
            {
                return;
            }
            var emailField = 'subscribe_email-' + fields[1];
            $(id).observe('click', function(event)
            {
                ASD.prepareTextFieldWithInfoTextToSubmit(emailField);
                ASD.submitSubscribeWidget(id, fields[1]);
            });

            $(emailField).initText = $F(emailField);
            $(emailField).observe('focus', function(event)
            {
                ASD.removeTextboxText(emailField);
            });
            $(emailField).observe('blur', function(event)
            {
                ASD.setTextboxText(emailField);
            });
        }
    });
    // left nav expansion if body is shorter
    ASD.expandLeftNavForShortBody();
    ASD.setAnchorToExternalToPopNewWindow();
    // OpenCMS Slot
    var footer = $('ft');
    if (footer)
    {
        var footerOffset = $('ft').positionedOffset();
        if (footerOffset && footerOffset.top < 600)
        {
            $$(".cms-content-slot-placeholder").each(
                function(slot)
                {
                    var slotOffset = $(slot).positionedOffset();
                    if (slotOffset.top <= footerOffset.top)
                    {
                        slot.style.height = (footerOffset.top - 100) + "px";
                    }
                }
                );
        }
    } // end if footer

    // page: exception
    var displayErrors = $('displayErrors');
    if (displayErrors)
    {
        Event.observe(displayErrors, 'click', function()
        {
            var exception = $('exception');
            if (exception)
            {
                exception.toggle();
            }
            var exceptionContent = $('exception-content');
            if (exceptionContent)
            {
                exceptionContent.toggle();
            }
        });
    }
});



