$(document).ready(function(){
	
	var announcement = false;
	if (announcement) { make_announcement('test.'); }
	
		loginLightbox('a.login');
		formHints();	
		killColumn('#secondary');
		
		dropDownMenu('#gateways');
		dropDownMenu('#manu');
		
		positionHiddenGateways('#g-prospective');
		positionHiddenGateways('#g-current');
		positionHiddenGateways('#g-faculty');
		positionHiddenGateways('#g-business');
		centerBalls();
		
		
		//if Nate's authentication script is loaded, see if there's already a session.
	  	if(!(typeof authLoaded=="undefined")) {
			//If we couldn't check to see whether they had a session or not during 
			//the page generation, we *could* figure it out after the fact.  However, that's
			//rather janky.
	  		//checkForExistingSession();
	  		//bind the logout function to the logout link, and when it finishes posting
	  		$('a.logout').live('click', function() {
	  			logout(function() { 
	  				//consolelog("logout complete, reloading");
	  				window.location.reload(); 
  				} );
	  			return false;
			} );
	  	}
}); //END jQuery

function formHints() {
	$('input.formhint').each(function() {
		$(this)
		.data('default', $(this).val())
		.addClass('inactive')
		.focus(function() {
			$(this).removeClass('inactive');
			if ($(this).val() == $(this).data('default') || '') {
				$(this).val('');
			}
		})
		.blur(function() {
			var default_val = $(this).data('default');
			if ($(this).val() == '') {
				$(this).addClass('inactive');
				$(this).val($(this).data('default'));
			}
		});
	});
} //end formHints()


function killColumn(column) {
	// this function checks to see if a column is empty, and adjusts the width of adjacent div accordingly
	if($(column).children().length == 0) {
		$('#main').css({
				'width': '87em'
			});
	}
}//end killColumn()

function dropDownMenu(menuID) {
	//this function adds cross-browser/more stylish drop down effect to the css-made suckerfish drop down
	$(menuID+' li ul').css({
		    display: "none",
		    left: "auto"
		  });
		  $(menuID+' li').hoverIntent(function() {
		    $(this)
		      .find('ul')
		      .stop(true, true)
		      .fadeIn('fast');
		  }, function() {
		    $(this)
		      .find('ul')
		      .stop(true,true)
		      .delay(50)
		      .fadeOut('fast');
		  });
}//end dropDownMenu function


function positionHiddenGateways(li_id)
{
	
	// ->Sets css left property to "0" instead of auto, which is default for dropdowns

	var hidden_menu = $(li_id+' .active');
	if ($(hidden_menu).children('.column3').length == 1) {
		// There is a 3rd column, move to the left
		var width3 = hidden_menu.outerWidth() * .31;  // 45/145-width of column(%) divided by width of total menu width(%)
		$(hidden_menu).css({
			    display: "none",
			    left: -(width3-1)
			  });
	} else {
		// No 3rd column
		$(hidden_menu).css({
	    display: "none",
	    left: "1px"
	  });
			
	}
	
} //end positionHiddenGateways()



function centerBalls() {
	// ->Centers the balls on the homepage slideshow 
	var ballsWidth = $('.ws_bullets').width();
	var abs_right = (960 - ballsWidth)/2;
	
	$('.ws_bullets').css({right: abs_right});
} //end centerBalls()

function lightBoxMessage(msg) {
    $('body').css('overflow-y', 'hidden'); // hide scrollbars
    
    //make dark overlay
    $('<div id="overlay"></div>')
      .css('top', $(document).scrollTop())
      .css('opacity', '0.7')
      .css('z-index', '99999')
      //.animate({'opacity': '0.5'}, 'slow')
      .appendTo('body');
    
    //make lightbox container  
    $('<div id="lightbox"></div>')
    .css('z-index', '999999')
      //.hide()
      .appendTo('body');
    
    $('<div id="inner" style="background: #ddd; min-width: 400px; padding: 15px 35px 40px 30px;">light box here</div>').appendTo('#lightbox');
    positionLightbox();
    
    if(/^https?:\/\//.test(msg)) {
    	console.log("loading " + msg + " into new div");
    	$('#inner').load(msg);
    }else {
    	console.log("writing" + msg + " into new div");
    	$('#inner').html(msg);
    }
    
	//ESC key will also remove the lightbox
	$(document).keyup(lightBoxKeyHandler);
    
	return false;
}

//START - FUNCTIONS FOR LOGINLIGHTBOX
//--------------------------------------------

function make_announcement(info) {
	$('<div id="announcement_popup" style="height: 30px; background: #F5828F; border: 1px solid red; text-align: center;  color: white; display: none;">' + info + '<a href="#" id="closeit" style="margin-left: 25px; color: black;">Close</a></div>').prependTo('body');
	
	
	if(!$.cookie('hideTopBar')) $("#announcement_popup").fadeIn("slow");
	$("a#closeit").click(function() {
	    $.cookie('hideTopBar', 'true', { expires: 1 });
	    $("#announcement_popup").fadeOut("slow");
	    return false;
	});
}

function make_announcement_test() {
	$('body').css('overflow-y', 'hidden'); // hide scrollbars
  
  //make dark overlay
  $('<div id="overlay"></div>')
    .css('top', $(document).scrollTop())
    .css('opacity', '0.7')
    .css('z-index', '99999')
    //.animate({'opacity': '0.5'}, 'slow')
    .appendTo('body');
  
  //make lightbox container  
  $('<div id="lightbox"></div>')
  .css('z-index', '999999')
    //.hide()
    .appendTo('body');			

//make inner container to hold lightbox content
  $('<div id="inner">ok</div>')
    .appendTo('#lightbox');
}



function loginLightbox(trigger) {
  $(trigger).click(function(e) {
  	
    $('body').css('overflow-y', 'hidden'); // hide scrollbars
    
    //make dark overlay
    $('<div id="overlay"></div>')
      .css('top', $(document).scrollTop())
      .css('opacity', '0.7')
      .css('z-index', '99999')
      //.animate({'opacity': '0.5'}, 'slow')
      .appendTo('body');
    
    //make lightbox container  
    $('<div id="lightbox"></div>')
    .css('z-index', '999999')
      //.hide()
      .appendTo('body');			

	//make inner container to hold lightbox content
    $('<div id="inner"></div>')
      .load('https://www1.kvcc.edu/forms/loginform.html #login_box', function() {
        positionLightbox();
			makeFormHints();
			makeFormHints_password();
			makeActiveLogin();
      })
      .appendTo('#lightbox');
    
	//ESC key will also remove the lightbox
	$(document).keyup(lightBoxKeyHandler);
    
	return false;
  	});

	//Clicking outside of the login window will remove lightbox
	$('#overlay').live('click', function() {
        removeLightbox();
      });
	
	//see if Nate's login stuff has been loaded, and if so associate it with the login button.
	if(typeof authLoaded=="undefined") {
		//give us a visual warning if some update smashed the login.js inclusion
		window.status="No login routines loaded.";
	}else {
		//attach the processLogin function to the login button
		$('#login').live('click', loginFromLightBox );
		//window.status="Login loaded.";
	}
  
} //end loginLightbox()

/*Define this as its own function so we can unbind it when the lightbox disappears */
function lightBoxKeyHandler(e) {
  	if (e.keyCode == 27) { $('#overlay').click(); }   // 27 == esc key
  	//again, check to see if Nate's login stuff has been loaded, and 
  	//if so check to see if they hit enter in the login form
  	if(!(typeof authLoaded=="undefined")) {
	  	//also call processLogin if the user hits the enter key
	  	if (e.keyCode == 13) { loginFromLightBox(); }   // 13 == enter key
  	}
}


var lastUsedUsername='';
//handle the attempt to login, regardless of whether it came from a click or enter
function loginFromLightBox() {
	var un=$('#user_name').val();
	var pw=$('#password').val();
	lastUsedUsername=un;
	//if the embedding page defined a javascript function to call after a successful login, grab it 
	if(typeof requestedPostLoginFunction!='undefined') {
//		consolelog("using specifically requested post-login function " + requestedPostLoginFunction);
		postLoginFunction=requestedPostLoginFunction;
	}else { //otherwise, just plan to refresh the page on successful login
		postLoginFunction=function() {
			window.location.reload();
			};
	}
	//consolelog("attempting loginFromLightBox");	
	attemptLogin(function(result) { 
		window.status= 'login status: ' + result; 
		if(result==1) {
			setUsernameLink();
			removeLightbox(); 
			$('.notloggedinmenu').hide();
			$('.loggedinmenu').show();
			//should set the my valley link here, but we'll need to get their username
//			$('#myvalleylink').html(lastUsedUsername);
			postLoginFunction();
		} 
	}, un, pw, 'user_name_error', 'password_error', 'general_error' );
	return false;
}

function setUsernameLink() {
	lazyCheckSession(function(un) {
		//consolelog("lazy session check says " + un);
		if(un==null || un=='') {
			return false;
		}
		$('#myvalleylink').html(un).show();
		});
}

/* See if the current user already (likely) has a valid session, based on their cookies.  
 * If so, replace the login link with a logout link
 */
function checkForExistingSession() {
//	consolelog("checking for existing session");
	lazyCheckSession(setLogoutLink);
}

function setLogoutLink(result) {
	if((typeof result)!='undefined' && result!=null && result!="") {
		//consolelog("would set logout link here based on result " + result);
		$('.login').html(result + " - logout");
	}
}

function positionLightbox() {
	
  var top = ($(window).height() - $('#lightbox').height()) / 4;
  var left = ( $(window).width() - $('#lightbox').width()) / 2;
	
  $('#lightbox')
    .css({
      'top': top + $(document).scrollTop(),
      'left': left
    })
    .fadeIn();

}// end positionLightbox()



function removeLightbox() {
  $('#overlay, #lightbox')
    .fadeOut('slow', function() {
      $(this).remove();
      $('body').css('overflow-y', 'auto'); // show scrollbars
    });
  $(document).unbind("keyup", lightBoxKeyHandler);
//  consolelog("removed lightbox keyup handler");
}// end removeLightbox()



function makeFormHints() {
	
	//hide all labels
	$('label').hide();

	//for all inputs 
	//store the alt attribute as the default,
	//make the hint by setting the input-text (value) to that default
	$('.clear').each(function() {
		$(this).data('default', $(this).attr('alt'));
		$(this).val($(this).data('default'));
	
	//slightly gray out the hint
	//on focus, clear the input text if it is the stored default
	//on blur, if the input is empty, restore the form hint
    $(this)
      .addClass('inactive')
      .focus(function() {
        $(this).removeClass('inactive');
        if($(this).val() == $(this).data('default') || '') {
          $(this).val('');
        }
      })
      .blur(function() {
        var default_val = $(this).data('default');
        if($(this).val() == '') {
          $(this).addClass('inactive');
          $(this).val($(this).data('default'));
        }
      });
 	 });
}// end makeFormHints()



function makeFormHints_password() {
	$('.clear_password').hide();

	// Insert dummy input
	$('<input id="dummy_password" type="text" title="Enter your password" name="dummy_password" value="password" tabindex="101"/>')
		.insertAfter('.clear_password')
		.addClass('inactive')

	//On focus, hide the dummy input, 
	//show the real input, and focus on it
		.focus(function () {
			$(this).hide();
			$('.clear_password').show().focus();
			 });
	
	//On blur, if you leave the real input blank
	//hide the real input
	//re-show the dummy input
		$('.clear_password').blur(function() {
			if($('.clear_password').val() == '') {
				$(this).hide();
				$('#dummy_password').show();
			}
		});
}// end makeFormHints_password()



function makeActiveLogin() {
	//if both the username and the password contain user input
	//make the login button light up
	$(document).ready(function(){
	$('.login_form').live('keyup', function(){
		if($('#user_name').val() != 'user name' &&
			$('#user_name').val() != '' &&
			$('#password').val() != '') 
			{
			$('#login').css('color', '#00A0C4');  //bright color text
			}
	
		if( $('#user_name').val() == 'user name' ||
			$('#user_name').val() == '' ||
			$('#password').val() == '') {
			$('#login').css('color', '#929292'); //grayed out text
			}	
	});	
});
}// end makeActiveLogin()


//END - FUNCTIONS FOR LOGINLIGHTBOX
//--------------------------------------------




/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);






/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : cookie_encode(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function cookie_encode(string){
	//full uri decode not only to encode ",; =" but to save uicode charaters
	var decoded = encodeURIComponent(string);
	//encod back common and allowed charaters {}:"#[] to save space and make the cookies more human readable
	var ns = decoded.replace(/(%7B|%7D|%3A|%22|%23|%5B|%5D)/g,function(charater){return decodeURIComponent(charater);});
	return ns;
}



















