mobiledetect = new RegExp(/android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i);
iphone = new RegExp(/ip(hone|od)/i); //test for iphone; use CSS3 animations, otherwise use JS
mobile = false;

if(mobiledetect.test(navigator.userAgent)){
	mobile = true;
}
//check the override cookie:
var cookies=document.cookie.split(";");
if(cookies.length != 0 ){
    //mobile style override based on cookie setting:
    for (var i=0; i<cookies.length; i++){
    	var cookieName = cookies[i].substr(0,cookies[i].indexOf("="));
        cookieName = cookieName.replace(/^\s+|\s+$/g,"");  
        if (cookieName.indexOf('urstyle_override') != -1){
        	if (cookieName.indexOf('_cms') == -1){
        		//normal route:
	            var exp = new RegExp('urstyle_override=','gi');
	            var dataStr = cookies[i].replace(exp, '');
	            
	            dataStr = unescape(dataStr);
	            exp = new RegExp('view=','gi');
	            dataStr = dataStr.replace(exp, '');  
	            override = dataStr.replace(/^\s+|\s+$/g,"");
        	}    
        	else{
        		//cascade only:
        		if( (window.location.hostname == 'webapps.richmond.edu') || (window.location.hostname == 'cas.richmond.edu') ){
        			var exp = new RegExp('urstyle_override_cms=','gi');
    	            var dataStr = cookies[i].replace(exp, '');
    	            
    	            dataStr = unescape(dataStr);
    	            var exps = new Array(new RegExp('view=','gi'), new RegExp('&cms=true'));
    	            for(var re=0; re<exps.length; re++){
    	            	dataStr = dataStr.replace(exps[re], '');  
    	            }	
    	            override = dataStr.replace(/^\s+|\s+$/g,"");
        		}
        	}
        }
    }     
}
if( (typeof(override) != 'undefined') && (override == 'standard') ){
	mobile = false;
	//make sure the style-override option is visible:
	$("#style-toggle").ready(function(){
		$("#style-toggle").show();
		$("#style-toggle").css({
			'margin-top': '-30px'
		});
	});
}
else if( (typeof(override) != 'undefined') && (override == 'mobile') ){
	mobile = true;
}


//this tests the browser versions for CSS3 compatability:
var Browser = function(){
	this.version = 0;
	this.browserReg = new RegExp(/AppleWebKit|Firefox|Chrome|Safari|IE|Opera|RockMelt/);
	this.agent = this.browserReg.exec(navigator.userAgent);	
	this.css3versions = {
			'AppleWebKit': 50,
			'Firefox' : 4,
			'Chrome': 10,
			'Safari': 4,
			'IE': 9,
			'Opera': 10,
			'RockMelt': 0
	};
	if(this.agent != null){
		this.start = navigator.userAgent.search(this.agent);
		this.start += String(this.agent).length;
		if(this.agent[0] != 'IE'){
			this.start++;
		}
		this.version = parseInt(navigator.userAgent.substring(this.start,this.start+2));
	}	
};
var b = new Browser();
if(b.browserReg.test(navigator.userAgent)){
	eval('var b_t = b.css3versions.'+b.agent+';');
	if(b.version >= b_t){
		css3 = true;
	}
}	

//nostyle may be set to true prior to calling loader.js to leave the page unstyled. 
//animation and basic UI JS will still load.
if( (typeof(nostyle) != 'undefined') && (nostyle == true)){
	nostyle = true;
}
else{
	//install font css
	/*var link = document.createElement('link');
	link.type = 'text/css';
	link.media = 'screen';
	link.rel = 'stylesheet';
	link.href = assetsUrl+"/styles/kp3/fonts.css";
	$("head").append(link);
	//this was moved to the DOM.
	*/
	
	if(mobile == true){
		//mobile
		$('body').ready(function(){
			$('body').addClass('mobile');
		});	
		 
		var link = document.createElement('link');
		link.type = 'text/css';
		link.media = 'screen';
		link.rel = 'stylesheet';
		link.href = assetsUrl+"/styles/kp3/mobile.css";
		$("head").append(link);
		
		var link = document.createElement('link');
		link.rel = 'apple-touch-icon';
		link.href = "http://www.richmond.edu/_common_KP3/images/_global_/mobile/icon.png";
		$("head").append(link);
		
		var meta = document.createElement('meta');
		meta.content = "initial-scale=1.0, user-scalable=yes, width=device-width";
		meta.name = 'viewport';
		$("head").append(meta);
		
		var m = new LoadTimer();
		m.object = 'MobileUi';
		m.timeout = 'mui_timeout';
		m.self = 'mui';
		m.__construct();
	}
	else{
		//standard
		var link = document.createElement('link');
		link.type = 'text/css';
		link.media = 'screen';
		link.rel = 'stylesheet';
		
		if(typeof(assetsUrl) != 'undefined' ){
			link.href = assetsUrl+"/styles/kp3/default.css";
		}
		else{		
			link.href = "http://assets.richmond.edu/styles/kp3/default.css";
		}
		$("head").append(link);
		
		//if not CSS3 compliant, load the legacy.css
		if(css3 != true){
			var link = document.createElement('link');
			link.type = 'text/css';
			link.media = 'screen';
			link.rel = 'stylesheet';
			link.href = assetsUrl+"/styles/kp3/legacy.css";
			$("head").append(link);
		}
		
		//correct the menu item spacing (since flex-box failed)	
		$("#menu").ready(function(){
			/*
			 * This has to wait for the CSS to be applied and then calculate the widths:
			 */
			var menu_timeout;
			
			function checkMenuStyle(){
				if($("#menu").children().find('a:last').css('padding-left') == '12px'){
					clearTimeout(menu_timeout);
					spaceMenu();
				}
				else{
					menu_timeout = setTimeout(function(){
							checkMenuStyle();
						}, 10);
				}
			}	
			
			function spaceMenu(){
				var maxMenuWidth = 972; //this value equals the CSS declaration
				var totalItemWidth = 0;
				var padding = 12; //same as L and R padding from CSS
				
				var itemCount = $("#menu").children().length;
				
				$("#menu").children().find('a span').each(function(){
					totalItemWidth += $(this).outerWidth() + 26; //we have 24px of padding L and R and a border
				});
				
				if(totalItemWidth > maxMenuWidth){
					var size = parseInt(maxMenuWidth/(itemCount))-(itemCount);
					$("#menu").find('a, span').css('max-width', size);
					//if the span element is taller than its parents, shrink the text size:
					$("#menu").children().find('a span').each(function(){
						if($(this).height() > $(this).parents('.item').height()){
							$(this).css('font-size', '0.7em');
						}
					});
					
				}
				else{
					//divide up the extra space and add to the a tag paddings
					var paddAdd = Math.floor((maxMenuWidth - totalItemWidth)/(itemCount*2)); //times 2 for L and R padding
					$("#menu").children().find('a').css({
						'padding-left' : (padding+paddAdd-2) + 'px', //minus 2 for the border elements
						'padding-right' : (padding+paddAdd-2) + 'px'
					});
					
				}
			
			}
			
			checkMenuStyle();

		});
		$("#submenu").ready(function(){
			if( ($("#submenu").length > 0) && ($("#menu").children('.on').length > 0) ){
				//add the submenu connector
				$("#menu-wrap").after('<div id="menu-connector"></div>');
				//find the .on menu element:
				var right = ($("#top-region").outerWidth() - $("#menu").innerWidth())/2;
				right = right + $("#submenu").outerWidth();
				var width = $("#menu").width() - $("#submenu").outerWidth() - $("#menu").children('.on').position().left;
				
				$("#menu-connector").width(width + 3).css('right', right - 3);
			}	
		});
		
		$('body').ready(function(){
			//hide the search and school bar in the top section and setup click events:
			if(window.location.href.indexOf("www.richmond.edu") == -1){
				$("#top-search, #schools-toolbar").hide();
			}
			else{
				$('#schools-toolbar-toggle, #top-search-toggle').addClass('on');
			}
			$('#schools-toolbar-toggle, #top-search-toggle').click(function(){
				if($(this).is('.on')){
					$(this).removeClass('on');
					$('#'+$(this).attr('target')).slideUp();
				}
				else{
					$(this).addClass('on');
					$('#'+$(this).attr('target')).slideDown(300);
				}
				
			});
		});	
		
	}
	
	//in both mobile and standard, allow for view toggling view the footer links:
	$('#footer').ready(function(){
		$("#style-toggle span").bind('click', function(){
			$.ajax({
				url: assetsUrl+'/actions/set/style-override.php?name=urstyle_override',
				type: "GET",
				dataType: "jsonp",
				data: {view: $(this).attr('target')},
				success: function(data){
					eval(data);
					window.location.reload();
				}
			});	
		});
	});	
}	

//set the print css:
var link = document.createElement('link');
link.type = 'text/css';
link.media = 'print';
link.rel = 'stylesheet';
link.href = assetsUrl+"/styles/kp3/print.css";
$("head").append(link);

//check if in cms mode:
if( (window.location.hostname == 'cas.richmond.edu')||(window.location.hostname == 'vmtrain.richmond.edu') ){
	var script = document.createElement('script');
	script.type='text/javascript';
	script.src = assetsUrl+'/scripts/kp3/cms/jquery-style-override.js';
	$("head").append(script);
}
