// CREATE OBJECT FOR UNIQUE NAME SPACE

if (aliceblue === undefined) var aliceblue = {};


// remap jQuery to $
(function ($){

	// Cache global object for faster access inside closure
	var ab = aliceblue;

	// CALL BIND EVENTS FUNCTION ON DOCUMENT READY

	$(document).ready(function() {
		
		// Is the global projectList ever used?
		if (typeof projectList == "undefined") {
			return false;
		}

		ab.init();

		if ((/iPhone|Android/i).test(navigator.userAgent)) {
			addEventListener("load", function() {
				setTimeout(function(){ window.scrollTo(0, 0); }, 0);
			}, false);
		}

		return true;
	});

	ab.getProjectPositions = function () {
		$('ul.projectList li').each(function (position) {
			var id = ab.getProjectId($(this)),
				project = ab.map.projects[id];
			
			// add position to both entries in the lookup table
			if (project) {
				project.position = position;
				project = ab.map.projects[project.name];
				project.position = position;
			}
			else {
				// add pseudo-project for last item
				if ($(this).attr('id') === 'lastItem') {
					project = {};
					project.position = position;
					project.id = 'lastItem';
					project.name = 'wir-stehen-dahinter';
					project.slides = [];
					ab.map.projects['wir-stehen-dahinter'] = project;
					ab.map.projects['lastItem'] = project;
				}
			}
		});
	};


	/**
	 * Updates the hash in the address bar; typically, this happens if the user
	 * executes an action that is equivalent to clicking a link, e.g., opening
	 * a slide.
	 *
	 * Depending on whether or not project and slide ids are supplied, the
	 * generated hash will be of the form:
	 *
	 * 1. /#!
	 * 2. /#!/projekte/<project name>
	 * 3. /#!/projekte/<project name>/<slide name>
	 *
	 * @param {Number} projectId The project id
	 * @param {Number} slideId The slide id
	 */
	ab.updateHash = function (projectId, slidePos) {
		var project, slide, url = window.location.href.split(/#/)[0] + '#!';

		project = ab.map.projects[projectId];

		if (project) {
			url = url + '/projekte/' + project.name;
			slide = project.slides[slidePos];

			if (slide) {
				url = url + '/' + slide.name;
			}
		}

		if (window.location.toString() !== url) {
			window.location = url;
		}
		
		return false;
	};
	

	/**
	 * Finds and replaces all local links in the given HTML data; local links are
	 * defined as anchor-tags whose `href' attribute either points to the domain
	 * on which the site is currently hosted or that begin with a `/'. Each
	 * link is turned into a local link using the `#!' form (unless the link
	 * already contains a `#').
	 *
	 * @param {jQuery} data HTML collection.
	 */
	ab.convertLocalLinks = function(data) {
		var root = window.location.href.split(/#/)[0],
			host = new RegExp('(' + root + '/|^/)');

		// Find all local links in the given element
		data.find('a[href^="' + root + '"], a[href^="/"]').each(function () {
			var $this = $(this), href = $this.attr('href');

			// Convert to internal link unless it already is
			if (!(/#/).test(href)) {
				$this.attr('href', href.replace(host, '$1#!/'));
			}
		});
		
		return false;
	};

	/** Parses the given hash and returns a mapping to slide and project information */
	ab.parse = function(hash) {
		var project, slide, map, match =
			(/#!\/projekte\/([^\/]+)(?:\/([^\/]+))?/).exec(hash || window.location.hash || '');
		
		if (ab.map && match && match.length >= 2) {
			project = ab.map.projects[match[1]];
			if (project) {
				map = {};
				map.project = { id: project.id, name: project.name, position: project.position };
				
				if (match.length >= 3 && match[2]) {
					slide = project.slides[match[2]];
					map.slide = { id: slide.id, name: slide.name, position: slide.position };
				}
			}
		}
		
		return map;
	};


	/**
	 * @returns the id of the given project
	 * @param {jQuery} the project element
	 */
	ab.getProjectId = function ($project) {
		return parseInt(/(?:project_id_(\d*))?/.exec($project.attr('id'))[1], 10)	|| 0;		
	};

	/** @returns the extended object of the project with the given id */
	ab.getProject = function (id) {
		if (id !== 'lastItem') {
			return $('ul.projectList li[id="project_id_' + id + '"]:first');
		}
		else {
			return $('ul.projectList li#lastItem');
		}
	};
	
	/** @returns the position of the project with the given id; or zero */
	ab.getProjectPosition = function (id) {
		// return ab.getProject(id).prevAll('li').size();
		var project = ab.map.projects[id];
		return project ? project.position : 0;
	};

	ab.getCurrentProject = function () {
		return $('ul.projectList li.currentProject:first');
	};

	/** @returns the id as integer of the first project that has the currentProject class. */
	ab.getCurrentProjectId = function () {
		return ab.getProjectId(ab.getCurrentProject());
	};
	
	/** @returns the position in the project list of the first project has the currentProject class; or zero. */
	ab.getCurrentProjectPosition = function () {
		return $('ul.projectList li.currentProject:first').prevAll('li').size();
	};
	
	ab.getSlide = function (id, $slides) {
		$slides = $slides || $('.slideshow:first li');
		return $slides.filter('li.slide[id="slide_' + id + '"]:first');
	};

	ab.getSlideId = function ($slide) {
		return parseInt(/(?:slide_(\d*))?/.exec($slide.attr('id'))[1], 10) || 0;
	};
	
	ab.getSlidePosition = function (id, $slides) {
		return ab.getSlide(id, $slides).prevAll('li').size();
	};
	

	/** Updates the state according to the current hash. */
	ab.goToHash = function () {
		var $project, position = 0, hash = ab.parse(), $slideshow = $('.slideshow').first();

		if (hash) {
			ab.hash = hash;
			
			// calculate new position of project list
			$project = ab.getProject(hash.project.id);
			
			if ($project.length) {
				position = hash.project.position;
			}

			// handle pop-up and slideshow position
			if (hash.slide) {
			 	if (ab.isPopUpOpen) {
					// go to new position of slideshow if slideshow for project already open
					if (hash.project.id === parseInt($slideshow.attr('data'), 10)) {
						$slideshow.cycle(ab.hash.slide.position);
					}
					else { // close and re-open pop-up
						ab.closePopUp(null, ab.openPopUp);
					}
				}
				else {
					ab.openPopUp();
				}
			}
			else {
				ab.closePopUp();
			}
		}
		
		ab.goToProject(position);
		return true;
	};


	// INIT FUNCTION

	ab.init = function () {
		ab.debug = true;

		ab.detectUserAgent();    

		ab.initialContentLoaded = false;

		//Preload images for first project
		var $projectList = $(projectList),
		$projectListStructure = $projectList.clone(true),
		$firstProject = $projectList.find('li:first');

		$projectListStructure.find('li').each(function(index) {
			$(this).html('');
		});
		$projectListStructure.appendTo('.projects');

		//Load Gradients
		$projectListStructure.bind('loadingQueueDone', function() {
			ab.loadProjectImage($firstProject, $projectListStructure);	
		}).loadingQueue({
			debug: false,
			'images': [$('div.leftGradientMask').backgroundImageUrl(), $('div.rightGradientMask').backgroundImageUrl()]
		});

		ab.getProjectPositions();
		
		ab.projectSlideStates = {};
		
		ab.hash = {};
		ab.hash.project = {};
		ab.hash.project.id = ab.map.projects.blink.id;

		ab.isPopUpOpen = false;
		
		$(window).hashchange(ab.goToHash);

	};

	ab.loadProjectImage = function($project, $projectListStructure) {
		$project.bind('loadingQueueDone', function (event) {
			var $this = $(this),
				$currentProjectRow = $projectListStructure.find('#'+$this.attr('id'));
			
			$currentProjectRow.html($this.html()).addClass('imagesLoaded').fadeIn('slow');
			
			var $nextProject = $project.next();
			if ($nextProject.length > 0) {
				ab.loadProjectImage($nextProject, $projectListStructure);
			}
			else {
				$('.projectListButton.nextButton').fadeIn('fast');

				ab.initProjectVariables();

				ab.projectsButtonController();

				ab.bindEvents(); 

				ab.windowResize();

				ab.scalePopUp();

				ab.initialContentLoaded = true;

				ab.goToHash();
				
				$('.mainLoader').fadeOut('medium', function() {
					$(this).remove();
				});
			}
			
			
		}).loadingQueue({debug: false});
	};

	// DEBUG FUNCTION

	ab.log = function (msg) {
		if (ab.debug) {
			try {
				return this.console && console.log( "%s: %o", msg, this);
			}
			catch (e) {
				return false;
			}
		}
		else {
			return false;
		}
	};

	ab.alog = function(msg){
		if (ab.debug) {
			$('body').append('<div id="debug_ablog" style="margin-top:100px;z-index:10000;width:100%; height:100px; overflow:auto;border:1px solid grey;position:absolute;background-color:#fff;color:#000;"><h1 id="debug_ablog_header">Debug</h1><hr/><pre>'+ msg +'</pre></div>');
		}
	};

	ab.goToNext = function () {
		var current = ab.hash.project, $next, id;
		
		if (current && current.id !== undefined) {
			$next = ab.getProject(current.id).next();			
			if ($next.length) {
				id = $next.attr('id');
				ab.updateHash((id && id !== 'lastItem') ? ab.getProjectId($next) : 'lastItem');
			}			
		}
		return false;
	};

	ab.goToPrevious = function () {
		var current = ab.hash.project, $prev;
		
		if (current && current.id !== undefined) {
			$prev = ab.getProject(current.id).prev();
			if ($prev.length) {
				ab.updateHash(ab.getProjectId($prev));
			}					
		}
		return false;
	};
	
	ab.goToNextSlide = function () {
		var current = ab.hash.slide;
		if (current && current.position !== undefined) {
			ab.updateHash(ab.hash.project.id, ab.hash.slide.position + 1);
		}
	};

	ab.goToPreviousSlide = function () {
		var current = ab.hash.slide;
		if (current && current.position > 0) {
			ab.updateHash(ab.hash.project.id, ab.hash.slide.position - 1);
		}
	};
	
	// LIST EVENT HANDLERS

    ab.bindEvents = function () {
		var $body = $('body');
		
		if (ab.isMobile) {
			$('div.projects, div.projects li').swipe({
				swipeLeft: function (event) {
					event.stopPropagation();
					var $nextButton = $('.projectListButton.nextButton');
					if (!$nextButton.is(':hidden')) {
						ab.goToNext();
					}
				},
				swipeRight: function() {
					event.stopPropagation();
					var $prevButton = $('.projectListButton.prevButton');
					if (!$prevButton.is(':hidden')) {
						ab.goToPrevious();
					}
				}
			});
			
			$('.projectListButton.nextButton').bind('touchend', ab.goToNext);
			
			$('.projectListButton.prevButton').bind('touchend', ab.goToPrevious);

			$('.projectLink').swipe({ click: function (event) {
				event.preventDefault();
				ab.updateHash(ab.getProjectId($(this).closest('li')), 0);
				return false;
			}});
		}
		else {
			$('.projectListButton.nextButton').bind('click', ab.goToNext);

			$('.projectListButton.prevButton').bind('click', ab.goToPrevious);
			
			$('.projectLink').bind('click', function (event) {
				ab.updateHash(ab.getProjectId($(this).closest('li')), 0);
				return false;
			});	
		}
		
		$('.closeButton, .overlay').live('click', function (event) {
			ab.updateHash(ab.getCurrentProjectId());
		});
		

		$('.popUpButton.nextButton').live('click', ab.goToNextSlide);

		$('.popUpButton.prevButton').live('click', ab.goToPreviousSlide);
		
		$(window).resize(ab.scalePopUp);		
	};


	// INIT VARIABLES
	ab.initProjectVariables = function () {
	
		ab.numberOfProjects = numberOfProjects;
		
		ab.projectListPadding = parseInt($('.projectList').css('padding-left'),10);

		ab.gradientMaskWidth = parseInt($('.rightGradientMask').css('width'),10);
		
		if ($('body').hasClass('portrait')) {
			ab.projectListTweaking = -200;
		}
		else {
			ab.projectListTweaking = -50;
		}

		ab.isSliding = false;

		ab.projectWidth = $('.projectList .project:first').width() + parseInt($('.projectList .project:first').css('margin-right'), 10) * 2;		
	};


	// BROWSE PROJECTS

	ab.goToProject = function(position) {
		var offset, $projectList = $('.projectList');
			
		if (ab.isSliding) {
			$projectList.stop();
		}
		else {
			ab.isSliding = true;
		}
		
		offset = (position * ab.projectWidth) * -1;

		$projectList.animate({ left: offset }, 500, 'easeOutQuad', function () {
			ab.projectsButtonController();
			ab.isSliding = false;
		});
		
		$projectList.find('li').removeClass('currentProject');
		$projectList.find('li.project:eq('+position+')').addClass('currentProject');		
	};
	

	// BUTTON CONTROLLER
	
	ab.projectsButtonController = function () {
		var offset, threshold, projectList = $('.projectList');

		offset = projectList.size() > 0 ? projectList.offset() : { left: 0, top: 0 };
		threshold = (ab.numberOfProjects * ab.projectWidth) + offset.left + ab.projectListPadding + ab.gradientMaskWidth + ab.projectListTweaking;

		if (offset.left < 0 && ab.initialContentLoaded) {
			$('.projectListButton.prevButton').fadeIn('fast');
		}
		else {
			$('.projectListButton.prevButton').fadeOut('fast');
		}
		
		if ($(window).width() > threshold) {
			$('.projectListButton.nextButton').fadeOut('fast');
		}
		else if (ab.initialContentLoaded) {
			$('.projectListButton.nextButton').fadeIn('fast');
		}
	};

	
	// CALL PROJECTS BUTTON CONTROLLER ON RESIZE FUNCTION
	
	ab.windowResize = function () {
		$(window).resize(function() {
			ab.projectsButtonController();
		});
	};


	window.onorientationchange = function() {
		var orientation = window.orientation,
			$body = $('body');

		ab.setOrientation();
		ab.initProjectVariables();
		ab.projectsButtonController();
		
		setTimeout(function () { window.scrollTo(0, 0); }, 0);

		ab.goToHash();		
	};
	
	// OPEN POP UP
	
	ab.openPopUp = function (event) {

		var popUpId = ab.hash.project.id,
			popUp = $('.popUpWrapper:first'),
			loader = popUp.find('.loader:first'),
			cover = popUp.find('.cover'),
			coverImage =  cover.find('img:first'),
			coverImageSrc = $('#project_id_'+popUpId+' div.projectPreview img').attr('src'),
			slideshow = popUp.find('.slideshow').first();
		
		cover.show();
		popUp.find('.loader').show();
		coverImage.attr('src',coverImageSrc);
		popUp.animate({opacity: 'show'}, { duration: 1, queue: true });
		ab.scalePopUp();								

		$.ajax({
			type: "POST",
			url: 'home/getPage/',
			data: {
				'id': popUpId
			},
			success: function(data){

				var $data = $(data),
					$slideshowStructure = null,
					$slides = $data.find('li.slide');

				// Convert local links to #! syntax
				ab.convertLocalLinks($data);
								
				popUp.find('.slideshow').replaceWith($data);
				$slideshowStructure = $data;
				slideshow = popUp.find('.slideshow');
				
				// // Add Project ID to slideshow
				slideshow.attr('data', new String(popUpId));

				//Preload images for first slide
				$slides.first().bind('loadingQueueDone', function(event) {
					var $this = $(this),					
						$nextSlide = $this.next();		
					// //Füge erste Slide aus data in slideshow struktur ein
					$slideshowStructure.find('li:first').html($this.html()).addClass('imagesLoaded').find('img').show();
					
					//blende cover aus
					popUp.find('.cover').fadeOut('slow', function() {
					
						//blende loader aus
						loader.fadeOut('slow', function() {
							setTimeout(function() {
								//initialisiere slideshow
								slideshow.show();
								ab.slideshow(popUpId);
							
								//Zeige Pager Buttons
								$('.pager, .closeButton').fadeIn('slow');
								if ($('body').hasClass('iPhone')) {
									$slideshowStructure.find('li').each(function(index) {
										if (index > 0) {
											var content = $($slides.get(index)).html();
											$(this).addClass('imagesLoaded').html(content).find('img').show();					
										}
									});
								}
								else if ($slides.size() > 1 && !$('body').hasClass('iPhone')) {
									ab.loadSlideImages($slideshowStructure, $slides, 1);
								}
							}, 10);
						});
					
					});			
				}).loadingQueue({
					debug : true
				});
			}
		});
		
		ab.isPopUpOpen = true;
	};
	
	ab.loadSlideImages = function($slideshowStructure, $slides, slideNo){
		var currentDataSlide = $slides.get(slideNo);
		$(currentDataSlide).bind('loadingQueueDone', function() {

			var $this = $(this),
				nextSlideNo = slideNo + 1;
				$currentSlide = $slideshowStructure.find('li:eq('+slideNo.toString()+')');
			//Füge Slide in die slideshow struktur ein
			$currentSlide.html($this.html()).addClass('imagesLoaded').find('img').show();
			
			//Replace html5 elements when not on iOS
			if (!$('body').hasClass('iOS')) {
				if (!$currentSlide.hasClass('flashReplaced')) {
					ab.insertFlashVideo($currentSlide);							
				}
			}
			
			if ($('body').hasClass('iOS') || $('body').hasClass('safarihtml5')) {
				//Stop all players on cycle
				$('.html5media').each(function(index) {
					this.pause();
				});
			}
			
			//die loading funktion für die nächste slide aufrufen
			if ($slides.size() > slideNo) {
				ab.loadSlideImages($slideshowStructure, $slides, nextSlideNo);
			}
			else if ($currentSlide.is(':visible') || $slideshowStructure.find('li').last().index() === index){
				$('.popUpWrapper:first .loader').fadeOut('slow');
			}
		}).loadingQueue();
	};


	// CLOSE POP UP
	
	ab.closePopUp = function (event, callback) {
		var $popUpWrapper = $('.popUpWrapper'), cpid = ab.getCurrentProjectId();
		
		if ($popUpWrapper.is(':hidden')) {
			return false;
		}
		
		if($('body').hasClass('iOS') || $('body').hasClass('safarihtml5')){						
			//Stop all players on cycle
			$popUpWrapper.find('.html5media').each(function(index) {
				this.pause();
			});
			
			if ($('body').hasClass('iPhone')) {
				ab.resetImages($popUpWrapper.find('.slideshow').find('img'));				
			}
		}

		$popUpWrapper.animate({opacity: 'hide'}, { duration: 'fast', complete: function () {
				ab.isPopUpOpen = false;
				if (callback && typeof callback === 'function') {
					callback.call();
				}
			}
		});
		
		$popUpWrapper.find('.pager').html('');
		$popUpWrapper.find('.slideshow').html('');
		//$popUpWrapper.find('.cover img:first').removeAttr('src');		

		$popUpWrapper.find('.popUpButton').hide();

		// `forget' current slide
		ab.projectSlideStates[cpid] = 0;
		
		return true;
	};


	// SCALE POP UP FUNCTION
	
	ab.scalePopUp = function () {
	
		var basePopUpWidth = 675,
			basePopUpHeight = 900,
			viewportWidth = $(window).width(),
			viewportHeight = $(window).height(),
		
			currentWidthFactor = viewportWidth/basePopUpWidth,
			currentHeightFactor = viewportHeight/basePopUpHeight,
		
			currentWidth = currentWidthFactor + "em",
			currentHeight = currentHeightFactor + "em",
			
			$popUp = $('.popUp');

		if (currentWidth < currentHeight && currentWidthFactor >= 0.61 && currentWidthFactor <= 1) { /* no media queries in IE7/8 --> check thresholds (0.61 and 1) in js */
			$popUp.css('font-size', currentWidth);
		} else if (currentHeightFactor >= 0.61 && currentHeightFactor <= 1) { /* no media queries in IE7/8 --> check thresholds (0.61 and 1) in js */
			$popUp.css('font-size', currentHeight);
		}	
	};

	

	// SLIDESHOW
	
	ab.slideshow = function (projectId) {
		
		$('.popUp').each(function() {
			
			var element = $(this);
			var slideshow = element.find('.slideshow');
			var $slides = slideshow.find('li.slide');
			var slides = $slides.size();
			var nextButton = element.find('.nextButton');
			var prevButton = element.find('.prevButton');
			var pager = element.find('.pager');
			var links = [];
			var i = 0;
		
			
			if (slides < 2) {
				nextButton.hide();
				prevButton.hide();
				$slides.show();
			}
			else {
				if (ab.isMobile) {
					slideshow.swipe({
						swipeLeft: function () { 
							var $nextButton = $('.popUpButton.nextButton');
							if (!$nextButton.is(':hidden')) {
								ab.goToNextSlide();
							}
						},
						swipeRight: function () {
							var $prevButton = $('.popUpButton.prevButton');
							if (!$prevButton.is(':hidden')) {
								ab.goToPreviousSlide();	
							}
						}
					});
				}
				
				// Add pager links
				for (i = 0; i < slides; ++i) {
					links.push('<li><a href="#!/projekte/' +
						ab.hash.project.name + '/' + ab.map.projects[ab.hash.project.id].slides[i].name +
						'"><span class="blockIcon"></span></a></li>');
				}
				
				pager.append($(links.join('')));

				slideshow.cycle({
					fx: 'scrollHorz',
					timeout: 0,
					speed: 'medium',
					nowrap: 1,
					startingSlide: ab.hash.slide && ab.hash.slide.position ? ab.hash.slide.position : 0,
					before: function(currSlideElement, nextSlideElement, options, forwardFlag){
						var $nextSlideElement = $(nextSlideElement),
							$currSlideElement = $(currSlideElement);

						// if ($nextSlideElement.html() !== '' && !$nextSlideElement.hasClass('imagesLoaded')) {
						// 	element.find('.loader:first').show();
						// }

					},
					after: function(curr, next, options){
						var links = pager.find('li'),
							index = options.currSlide;
						
						links.removeClass('activeSlide');
						links.filter('li:eq('+index+')').addClass('activeSlide');
						
						prevButton[index === 0 ? 'hide' : 'show']();
						nextButton[index === options.slideCount - 1 ? 'hide' : 'show']();
					}
				});
			}
		});
	};

	
	ab.resetImages = function($images) {
		$images.each(function(index) {
			var img = this;
			img.parentNode.removeChild(img);
			img.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
			setTimeout(function() {
			  	img = null;				
			}, 6000);
		});

	};


	ab.insertFlashVideo = function (slide) {
		var $slide = $(slide),
			slideId = $slide.attr('id'),
			slideIdParts = slideId.split('_'),
			media = $slide.find('#mediaContainerContent_'+slideIdParts[1]),
			playerStyle = '',
			embedTag = '';

		embedTag +='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="mediaContainerContent_'+slideIdParts[1]+'" name="mediaContainerContent_'+slideIdParts[1]+'">';
		embedTag +='	<param name="movie" value="jw/player.swf">';
		embedTag +='	<param name="allowfullscreen" value="true">';
		embedTag +='	<param name="allowscriptaccess" value="always">';
		embedTag +='	<param name="wmode" value="transparent">';
		embedTag +='	<param name="bgcolor" value="#f1f1f1">';
		embedTag +='	<param name="flashvars" value="file='+ media.attr('src')+'&amp;autostart=false&amp;controlbar=over&amp;image='+ media.attr('poster')+'">';
		embedTag +='	<embed'; 
		embedTag +='		id="mediaContainerContent_100"';
		embedTag +='		name="mediaContainerContent_100"'; 
		embedTag +='		height="100%"'; 
		embedTag +='		width="100%"'; 
		embedTag +='		bgcolor="#f1f1f1"'; 		
		embedTag +='		src="jw/player.swf"'; 
		embedTag +='		allowscripaccess="always"'; 
		embedTag +='		allowfullscreen="true"'; 
		embedTag +='		flashvars="file='+ media.attr('src')+'&amp;autostart=false&amp;controlbar=over&amp;image='+ media.attr('poster')+'"';
		embedTag +='		type="application/x-shockwave-flash"/>';
		embedTag +='</object>';

		if ($slide.find('.audioPoster')) {
			var audioPoster = slide.find('.audioPoster');
			audioPoster.css('display','block');
			playerStyle = audioPoster.attr('style');
		}
		else {
			playerStyle = media.attr('style');
		}

		$slide.find('#mediaContainerContentWrapper_'+slideIdParts[1]).html(embedTag);
		$slide.find('#mediaContainerContentWrapper_'+slideIdParts[1]).attr('style', playerStyle);
		$slide.addClass('flashReplaced');
	};


	ab.setOrientation = function () {
		switch (window.orientation) {
		case 90:
		case -90:
			$('body').removeClass('portrait').addClass('landscape');
			break;
		default:
			$('body').removeClass('landscape').addClass('portrait');
			break;
		}
	};
	
	// DETECT USER AGENT
	
	ab.detectUserAgent = function () {
		var ua = navigator.userAgent;
		
		ab.isiPad = ((/iPad/i).test(ua));
		ab.isiPhone = ((/iPhone/i).test(ua));
		ab.isAndroid = ((/Android/i).test(ua));
		ab.isSafari5 = $.browser.safari() && $.browser.version.number() >= 5;

		ab.isMobile = ab.isiPad || ab.isiPhone || ab.isAndroid;
		
		if (ab.isiPad) {
			$('body').addClass('iPad iOS');
			ab.setOrientation();
		}
		else if (ab.isiPhone) {
			$('body').addClass('iPhone iOS');
			ab.setOrientation();
		}
		else if (ab.isSafari5){
			$('body').addClass('safarihtml5');			
		}
	};
})(window.jQuery);
