var iphone = new RegExp(/ip(hone|od)/i); //test for iphone; use CSS3 animations, otherwise use JS
//include the new integrated search module
document.write('<script type="text/javascript" src="http://'+window.location.hostname+'/_common_KP3/scripts/jquery-search.js"></script>');
document.write('<meta content="initial-scale=1.0, user-scalable=yes, width=device-width" name="viewport" />');

var mobileReady;

function MobileUi(){
	
	this.clickType;
	
	this.setTouchAnimation = mu_setTouchAnimation;
	this.setMenus = mu_setMenus;
	this.setHome = mu_setHome;
	this.resizeSecondaryImg = mu_resizeSecondaryImg;
	this.setMedia = mu_setMedia;
	this.setSearchResults = mu_setSearchResults;
	this.slideMenu = mu_slideMenu;
	this.setTabs = mu_setTabs;
	this.setTables = mu_setTables;
	
	this.location = {
			domain: window.location.hostname.split('.')[0],
			level: window.location.pathname.split('/').length - 1
	};
	
	this.search = new Search();
	
	this.cookie = {
			name: 'ur_mobile_style',
			dataEls: new Array('value')
	}
	
	this.__construct = function(){
		var obj = this;
		
		//configure bottom links to allow view toggling:
		$('#styleToggle').show();
		$("#styleToggle span").bind('click', function(){
			var type = obj.cookie.dataEls[0]+'='+$(this).attr('target');
			$.ajax({
				url: 'http://'+window.location.hostname+'/_common_/actions/set/cookie.php?name='+obj.cookie.name+'&method=mobilestyle',
				type: "POST",
				data: type,
				success: function(data){
					window.location.reload();
				}
			});	
		});
		
		var cookies=document.cookie.split(";");
		if(cookies.length != 0 ){
			//mobile style override based on cookie setting:
			for (var i=0; i<cookies.length; i++){
				
				/*
				 * On this we are finding the appropriate cookie (urexperts),
				 * and then chunking the string into pieces by:
				 * 1. removing the cookie name 
				 * 2. removing the POST data element name
				 * 3. splitting the netid set into an array
				 * 
				 *  unescaped, this cookie string looks like:
				 *  value=mobile&=&
				 */
				  var cookieName = cookies[i].substr(0,cookies[i].indexOf("="));
				  cookieName = cookieName.replace(/^\s+|\s+$/g,"");
				 
				  if (cookieName == obj.cookie.name){
					  var exp = new RegExp(obj.cookie.name+'=','gi');
					  var dataStr = cookies[i].replace(exp, '');
					  
					  dataStr = unescape(dataStr);
					  
					  for(var n=0; n<obj.cookie.dataEls.length; n++){
						  exp = new RegExp(obj.cookie.dataEls[n]+'=','gi');
						  dataStr = dataStr.replace(exp, '');  
					  }
					  
					  if(dataStr.indexOf('standard') != -1){
						  $('link[media="screen"]').attr('href', 'http://'+window.location.hostname+'/_common_KP3/styles/default-2.0.css');						  
						  $('meta[name="viewport"]').attr('content', "initial-scale=0.32, user-scalable=yes, height=device-height");
						  $("#styleToggle span[target='standard']").addClass('selected');
						  return false;
					  }
				  }
			}
			
		}
		$("#styleToggle span[target='mobile']").addClass('selected');
		
		//otherwise set up the mobile ui:
		obj.setMedia();
		
		if($(".secondary img, .showcase img").length > 0){
			obj.resizeSecondaryImg();
		}	
		
		obj.setTouchAnimation();
		obj.setMenus();
		
		obj.search.__construct();
		$("#wp_top_search").bind('submit', function(){
			obj.setSearchResults();
		});
		
		if( (obj.location.domain == 'www') || (obj.location.domain == 'qawww2') ){
			obj.setHome();
		}
		
		$(window).load(function(){
			window.scrollTo(0,1);
			mobileReady = obj;
		});
			
	};
	
}

function mu_setHome(){
	var obj = this;	
	
}

function mu_setSearchResults(){
	var obj = this;
	
	
	
}

function mu_setMedia(){
	var obj = this;
	
	$('.video, .slideshow').hide();
	
}

function mu_resizeSecondaryImg(){
	var obj = this;
	//resize secondary images
	$(".secondary img, .showcase img").width($('.copy').width()).show();
}

function mu_setMenus(){
	var obj = this;
	
	//add an index page link to main menus of non-www sites:
	if($('.siteName').text() != ''){
		$('.menu').prepend('<li><a href="http://'+window.location.hostname+'" class="site_home">'+$('.siteName').text()+' Home</a></li>');
	}	
	
	
	//add a siteName element to WWW:
	$('.urlogo').after('<div class="siteName"><a><span>Explore UR</span></a></div>');
	
	//add mobile-specific control elements:
	$(".siteName").after('<div id="search_toggle" class="toggle global" slide="#wp_top_search"></div>'+
			'<div id="subnav_toggle" class="toggle global" slide=".submenu"></div>');
	
	$('.siteName, #subnav_toggle, #search_toggle').wrapAll('<div id="nav_wrapper"></div>');
	
	$('.siteName').addClass('toggle').addClass('global').attr('slide', '.menu:first');
	$('.siteName a').removeAttr('href');
	
	//move the search box under the menu:
	$('#wp_top_search').insertAfter('.menu:first');
	
	//if no submenu exists hide the submenu button:
	if($('.submenu').length < 1){
		$("#subnav_toggle").hide();
		$(".siteName").css('width', '82%');
	}
	else{
		//change the DOM position of the submenu for top placement:
		$('.submenu').insertAfter('.menu:first');
	}
	
	//wrap link and text promos together respectively:
	if($('.column .link').length > 0){
		$('.column').append('<div id="link_wrapper"></div>');
		$('.column .link').appendTo('#link_wrapper');
	}
	if($('.column .text').length > 0){
		$('.column').append('<div id="text_wrapper"></div>');
		$('.column .text').appendTo('#text_wrapper');
	}
	
	
	//wrap search, menu, and submenu in a container and make slideable:
	$('.menu:first, .submenu, #wp_top_search').wrapAll('<div id="toggleTargets" style="overflow: hidden;"></div>');
	$('#toggleTargets').children().hide();//.addClass('up').hide();
	
	//wrap everything following toggleTargets in contentTargets:
	//This MUST go away. It causes in-page JS to run twice. 
	//take it out once the XSLT is updated with the correct DOM element.
	/*
	 * I did find a nice workaround http://stackoverflow.com/questions/5010943/can-i-prevent-code-in-a-script-element-from-running-again-when-i-manipulate-one
	 * This probably is breaking something somewhere else though. 
	 */
	if($("#contentTargets").length == 0){
		$('#toggleTargets').nextAll().find('script').attr('type', 'text/plain');
		$('#toggleTargets').nextAll().wrapAll('<div id="contentTargets"></div>');
	}
	
	//anywhere there is a bucket class, replace it with main:
	$(".promos .bucket").addClass('main').removeClass('bucket');
	
	//make the top toolbar links a footer element:
	$('.footer .notices').after('<div class="right"><div class="title">Top Links</div></div>');
	$('#top_toolbar ul:first').appendTo('.footer .right:first');
	
	//add toggle classes to the footer div's and their target ul's.
	$(".footer > div:not(.notices)").each(function(){
		$(this).children('.title').attr('slide', ".footer > div:eq("+$(this).index()+") ul").addClass('toggle');
	});
	
	$(".footer > div:not(.notices) > ul").each(function(){
		$(this).wrap('<div style="overflow: hidden;"></div>')
		$(this).addClass('up');
		if(iphone.test(navigator.userAgent)){
			$(this).css({
				'-webkit-transition' : '-webkit-transform 0.5s ease',
				'-webkit-transform' : 'translate3d(0,-'+$(this).height()+'px,0)'
			});
		}
	});	

	
	$('body').bind(obj.clickType.start, function(){
		obj.clickType.hasMoved = false;
	});
	
	$('body').bind(obj.clickType.move, function(){
		obj.clickType.hasMoved = true;
	});
	
	$('.toggle').bind(obj.clickType.end, function(){
		
		if(obj.clickType.hasMoved == false){
			var action = {
				el: $(this),
				slide: $($(this).attr('slide'))
			};
			
			function disable(item){
				action.el.parent().children().removeClass('on');
				//turn off a visible menu:
				item.removeClass('down').addClass('up');		
				
				if(iphone.test(navigator.userAgent)){
					item.css({
						'-webkit-transition' : '-webkit-transform 0.5s ease',
						'-webkit-transform' : 'translate3d(0,-'+item.height()+'px,0)'
					});
					
					if(action.el.is('.global')){
						$('#contentTargets, .footer:first').css({
							'-webkit-transition' : '-webkit-transform 0.5s ease',
							'-webkit-transform' : 'translate3d(0,-'+item.height()+'px,0)'
						});
					}	
					
					setTimeout(function(){
						item.hide();
						if(action.el.is('.global')){
							$('#contentTargets, .footer:first').css({
								'-webkit-transition' : '-webkit-transform 0s',
								'-webkit-transform' : 'translate3d(0,0,0)'
							});
						}	
					}, 500);	
				}
				else{
					item.slideUp(500);
				}
				
				
			}
			
			function enable(item){
				action.el.addClass('on');
				//turn on the active element:
				
				if(iphone.test(navigator.userAgent)){
					item.show().removeClass('up').addClass('down');
				
					item.css({
						'-webkit-transition' : '-webkit-transform 0s',
						'-webkit-transform' : 'translate3d(0,-'+item.height()+'px,0)'
					});
					
					if(action.el.is('.global')){
						$('#contentTargets, .footer:first').css({
							'-webkit-transition' : '-webkit-transform 0s',
							'-webkit-transform' : 'translate3d(0,-'+item.height()+'px,0)'
						});
					}	
					
					action.slide.css({
						'-webkit-transition' : '-webkit-transform 0.5s ease',
						'-webkit-transform' : 'translate3d(0,0,0)'
					});
					
					if(action.el.is('.global')){
						$('#contentTargets, .footer:first').css({
							'-webkit-transition' : '-webkit-transform 0.5s ease',
							'-webkit-transform' : 'translate3d(0,0,0)'
						});
					}	
				}
				else{
					item.removeClass('up').addClass('down');
					item.slideDown(500);
				}
			}
			
			
			//Logic:
			
			if(action.slide.is(':visible')){
				disable(action.slide);	
			}
			else{
				//test if a sibling item is already on; turn it off:
				if(action.el.parent().children('.on').length > 0){
					action.el.parent().children('.on').each(function(){
						disable($($(this).attr('slide')));
					});
					setTimeout(function(){
						enable(action.slide);
					}, 500);
				}
				else{
					enable(action.slide);
				}	
			}
			
			obj.clickType.hasMoved = false;
			return false;
		}	
	});
	
	//change the way the UR wordmark operates (native hyperlink is too "clickable" by accident):
	$('a.urlogo, a.urlogoSmall').each(function(){
		$(this).attr('target', $(this).attr('href'));
		$(this).removeAttr('href');
	});
	
	$('a.urlogo, a.urlogoSmall').bind(obj.clickType.end, function(){
		window.location.href = $(this).attr('target');
		return false;
	});
	
	//open the site menu if on an index page of a site; otherwise collapse it.
	/*if( (obj.location.domain == 'www') && (obj.location.level < 2) ){
		//but only do this if there is no emergency:
		if($('#alert_content').length == 0){
			$('.siteName').addClass('on');
			$('.menu:first').show();
			$('.promos:first').css('margin-top','16px');
		}	
	}*/
	
	//obj.setTabs(); //this is now called by collapsed content itself
	obj.setTables();

}

function mu_setTables(){
	var obj = this;
	
	var collapseH = 300;
	var origH;
	
	$('table').wrap('<div class="table-scroll"></div>');
	
	$(".table-scroll").each(function(){
		if($(this).height() > collapseH){
			$(this).css({
				height: collapseH+'px'
			});
			origH = collapseH;
		}	
		else{
			origH = $(this).height();
		}
		$(this).before('<div class="table-expand">Expand table</div>');
	});
	
	$('.table-expand').bind(obj.clickType.end, function(){
		var t = $(this).next();
		
		$(this).toggleClass('on');
		if($(this).is('.on')){
			$(this).text('Collapse table');
			t.width(t.children('table').width());
			t.height(t.children('table').height());
		}
		else{
			$(this).text('Expand table');
			t.width('100%');
			t.height(origH+'px');
		}
	});
	
}	

function mu_setTabs(){
	var obj = this;
	//set animation behavior of tab menus:
	var count = $('.tab').length - 1;
	$(".tabMenu li:eq("+count+")").ready(function(){
		if($(".tabMenu").length > 0){
			$(".tabMenu").css('position', 'relative');
			
			var w = 0;
			$(".tabMenu").children().each(function(){
				w += $(this).outerWidth(true);
			});
			
			
			$(".tabMenu").children().wrapAll('<div class="slideWrap"></div>');
			$(".tabMenu").append('<div class="shadow left"></div><div class="shadow right"></div>');
			
			
			var activeEl = $(".tabMenu .slideWrap li:first");
			
			$(".tabMenu .slideWrap").css({
				position: 'absolute',
				top: '0px',
				left: -1*(activeEl.position().left - ($(".tabMenu").width()/2) + (activeEl.outerWidth(true)/2)),
				width: w+'px'
					
			});
		
			$(".tabMenu .slideWrap li").bind('click', function(){
				$('body').unbind(obj.clickType.end);
				$(".tabMenu").unbind(obj.clickType.move);
				
				activeEl = $(this);
				$(".tabMenu").children('.slideWrap').animate({
					'left': -1*(activeEl.position().left - ($(".tabMenu").width()/2) + (activeEl.outerWidth(true)/2))
				}, 500);
				
				
				return false;
			});
			
			$(".tabMenu").bind(obj.clickType.start, function(e){	
				obj.slideMenu($(this), e);
			});
		}
		
	});
}


function mu_slideMenu(swipe, e, doHeight, noRebound){
	var obj = this;
	
	$('body').unbind(obj.clickType.end);
	
	e.clientX = eval(obj.clickType.x);
	e.clientY = eval(obj.clickType.y);
	var start_x = e.clientX;
	var start_y = e.clientY;
	
	var start_left = swipe.children('.slideWrap').position().left;
	var start_top = swipe.children('.slideWrap').position().left;
	
	swipe.bind(obj.clickType.move, function(e){	
		e.clientX = eval(obj.clickType.x);
		var moveByX = e.clientX - start_x;
		swipe.children('.slideWrap').css('left', moveByX + start_left);
		
		if(doHeight == true){
			e.clientY = eval(obj.clickType.y);
			var moveByY = e.clientY - start_y;
			swipe.children('.slideWrap').css('top', moveByY + start_top);
			
		}
		
		return false;
	});	

	if(noRebound != true){
		$('body').bind(obj.clickType.end, function(){
			swipe.unbind(obj.clickType.move);
			
			var lastPos = swipe.children('.slideWrap').width() - swipe.find('.slideWrap > *:last').outerWidth() - 20;
			
			//rebound left:
			if(swipe.children('.slideWrap').position().left > 0){
				swipe.children('.slideWrap').animate({
					'left': '0'
				}, 500);
				
			}
			//rebound right:
			else if(Math.abs(swipe.children('.slideWrap').position().left) > lastPos){
				swipe.children('.slideWrap').animate({
					'left': -1*lastPos
				}, 500);
				
			}
			//find element with the position closest to the start and lock that one in:
			else{
				var closestPos = lastPos +20;
				var activeEl;
						
				swipe.find('.slideWrap > *').each(function(){
					if(Math.abs($(this).offset().left) <= closestPos){
						closestPos = Math.abs($(this).offset().left);
						activeEl = $(this);
					}
				});
				
				swipe.children('.slideWrap').animate({
					'left': -1*activeEl.position().left
				}, 500);		
				
			}
			return false;
		});
	}
	return false;
}	


function mu_setTouchAnimation(){     
	var obj = this;
	
	//pick touch or click
	document.body.setAttribute('ontouchmove','return;');
	if(typeof document.body.ontouchmove == 'function'){
		obj.clickType = {
				start: 'touchstart',
				move: 'touchmove',
				end: 'touchend',
				x: 'event.changedTouches[0].clientX',
				y: 'event.changedTouches[0].clientY',
				hasMoved: false
		}
	}	
	else{
		obj.clickType = {
				start: 'mousedown',
				move: 'mousemove',
				end: 'mouseup',
				x: 'e.clientX',
				y: 'e.clientY',
				hasMoved: false
		}		
	}
	
	//on orientation change do these:
	window.onorientationchange = function(){
		obj.resizeSecondaryImg();
	}
}	
