var slideWidth = 0,
	slideHeight = 0,
	currentSlide = 0,
	totalSlides = 4
	slideNames = ["challenge", "process", "solution", "results"],
	slideAnimating = false,
	swipeStartPoint = 0,
	swipeMinDist = 100,
	sliceBadgeHeight = 0,
	lastSlice = null,
	currentSlice = null,
	clickedOnSlice = [0, 0, 0, 0],
	imageMode = 'large',
	isIpad = false,
	refWidth = 1024,
	refHeight = 768,
	pageWidth = null,
	pageHeight = null,
	mainContentRatio = null,
	clientPageURL = "client.html",
	clientPageTitle1 = "Midnight Oil Creative",
	clientPageTitle2 = "Case Study";
$(window).load(function () {
	if (page == "home") mainContentRatio = $('.slices').height() / $('.slices').width();
	else mainContentRatio = $('.showcase').height() / $('.showcase').width();
	// initial layout fix
	updateLayout();
});
$(document).ready(function () {
	pageWidth = document.body.clientWidth || window.innerWidth;
	pageHeight = document.body.clientHeight || window.innerHeight;

	if (screen.width <= refHeight && screen.height <= refWidth) {
		imageMode = 'medium';
	}

	if (pageWidth == 320 || pageWidth == 480) {
		toggleContent(false);
		//updateViewportSettings();
		overwriteIpadCSS('all and (max-width: 320px)', 'global/css/portrait-iphone.css');
		overwriteIpadCSS('all and (min-width: 321px)', 'global/css/landscape-iphone.css');
	}

	isIpad = navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null;
	// orientation support
	var supportsOrientationChange = "onorientationchange" in window,
		orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
	if (window.addEventListener) {
		window.addEventListener(orientationEvent, function () {

			pageWidth = document.body.clientWidth || window.innerWidth;
			pageHeight = document.body.clientHeight || window.innerHeight;

			toggleContent(false);
			updateLayout();
		}, false);
	} else {
		window.onresize = updateLayout
	}
	// image hover
	setupImageSwapping();
	switch (page) {
	case 'home':
		var htmlBgs = '<div class="bg-image" id="bg1"> <img alt="global/img/media/m-bg-' + imageMode + '.jpg" src="global/img/media/m-bg.jpg" class="bg"/> </div>'
		htmlBgs += '<div class="bg-image" id="bg2"> <img alt="global/img/media/f-bg-' + imageMode + '.jpg" src="global/img/media/f-bg.jpg" class="bg"/> </div>'
		htmlBgs += '<div class="bg-image" id="bg3"> <img alt="global/img/media/s-bg-' + imageMode + '.jpg" src="global/img/media/s-bg.jpg" class="bg"/> </div>'
		htmlBgs += '<div class="bg-image" id="bg4"> <img alt="global/img/media/d-bg-' + imageMode + '.jpg" src="global/img/media/d-bg.jpg" class="bg"/> </div>';
		$('body').prepend(htmlBgs);
		// slices fct for mouse over /out
		$('.slices .slice').live(isIpad ? 'click' : 'mouseenter', function () {
			currentSlice = $(this).index();
			if (isIpad) {
				if (++clickedOnSlice[currentSlice] == 2) {
					clickedOnSlice[currentSlice] = 0
					goToURL(clientPageURL + '?' + $(this).attr('id'));
					return true;
				}
			}
			// slice color
			if ($.browser.webkit || $.browser.mozilla) {
				$('.slices .slice img.top').each(function () {
					if ($(this).parent().index() != currentSlice) $(this)[0].style.display = "none";
					//$(this).addClass("transparent");
					else $(this)[0].style.display = "block";
					//$(this).removeClass("transparent");
				});
			} else {
				$('.slices .slice img.top').stop().css("opacity", "0");
				$(this).find("img.top").animate({opacity: 1}, {duration: 'fast',queue: false})
			}
			// badge sliding
			if ($.browser.webkit) {
				$('.slices .slice .badge').each(function () {
					if ($(this).parent().index() != currentSlice) {
						$(this)[0].style.bottom = " -" + sliceBadgeHeight + "px";
						//$(this)[0].style.display="none";
						//$(this).css("-webkit-transform", "translate(0, 0)");
					} else {
						$(this)[0].style.bottom = "0px";
						//$(this)[0].style.display="block";
						//$(this).css("-webkit-transform", "translate(0, -" + sliceBadgeHeight + "px)");
					}
				})
			} else {
				$('.slices .slice .badge').each(function () {
					if ($(this).parent().index() != currentSlice) $(this).css("bottom", "-" + sliceBadgeHeight + "px");
					else $(this).css("bottom", "0px");
				});
			}
			// bg update (switch)
			if ($.browser.webkit || $.browser.mozilla) {
				if (lastSlice != null) {
					$('#bg' + (lastSlice + 1) + '')[0].style.zIndex = 1;
					$('#bg' + (lastSlice + 1) + '')[0].style.visibility = "hidden";
					//$('#bg' + (lastSlice + 1) + '').addClass("transparent").css("z-index", 1);
				}
				$('#bg' + (currentSlice + 1) + '')[0].style.zIndex = 2;
				$('#bg' + (currentSlice + 1) + '')[0].style.visibility = "visible";
				//$('#bg' + (currentSlice + 1) + '').css({'z-index': 2}).show().removeClass("transparent");
			} else {
				if (lastSlice != null) $('#bg' + (lastSlice + 1) + '').css({
					"z-index": "1",
					"visibility": "hidden"
				});

				$('#bg' + (currentSlice + 1) + '').css({
					"visibility": "visible",
					"z-index": "2"
				});
			}
			lastSlice = currentSlice;
		});
		$('.slices .slice').live('mouseleave', function () {
			clearSliceSelection();
		});
		if (!isIpad) {
			$('.slices .slice').click(function () {
				goToURL(clientPageURL + '?' + $(this).attr('id'));
			})
		}
		break;
	case 'client':
		// show client content
		var q = window.location.search;
		var client = (q.length > 1) ? q.substring(1, q.length) : '';
		$(this).attr('title', clientPageTitle1 + ' - ' + parseClient(client)+' '+clientPageTitle2);
		var c = '<div class="bg-image"><img alt="global/img/media/' + ((client.substr(0, 1)).toLowerCase()) + '-bg-' + imageMode + '.jpg" src="global/img/media/' + ((client.substr(0, 1)).toLowerCase()) + '-bg.jpg" class="bg"/></div>';
		$('body').prepend(c);
		$('.showcase .nav div#' + client + '').show();
		for (i = 1; i <= 4; i++) $('.slides .inside .items').append('<img src="global/img/media/' + ((client.substr(0, 1)).toLowerCase()) + '' + i + '.jpg"/>');
		// share buttons
		changeShare(window.location, $('title').html());
		$('.fb').click(function () {
			openURL(fbURL);
		});
		$('.twitter').click(function () {
			openURL(twitterURL);
		});
		// slides menu
		$(".menu div").click(function (e) {
			doSlide($(this).index());
		});
		// arrow navigation for slides
		$(".nav-arrows img:nth-child(1)").click(function (e) {
			var tmp = currentSlide;
			if (tmp > 0) tmp--;
			else tmp = totalSlides - 1;
			doSlide(tmp);
		});
		$(".nav-arrows img:nth-child(2)").click(function (e) {
			var tmp = currentSlide;
			if (tmp < totalSlides - 1) tmp++;
			else tmp = 0;
			doSlide(tmp);
		});
		// slider
		$(".slides").live('touchstart', function (e) {
			swipeStartPoint = e.originalEvent.touches.item(0).pageX;
		}).live('touchmove', function (e) {
			if (e.originalEvent.touches.length == 1 && Math.abs(e.originalEvent.touches.item(0).pageX - swipeStartPoint) > swipeMinDist) {
				// navigate slides
				if (totalSlides > 0) {
					var tmp = currentSlide;
					if (e.originalEvent.touches.item(0).pageX > swipeStartPoint) {
						if (tmp > 0) tmp--;
					} else {
						if (tmp < totalSlides - 1) tmp++;
					}
					doSlide(tmp);
				}
			}
		}).live('touchend', function (e) {
			swipeStartPoint = 0;
		}); /**/
		break;
	}
	// replace background with HQ image
	$('.bg-image').backgroundImage();

	//
	$('#main #hotspotArea').click(function () {
		clearSliceSelection();
	});
});

function clearSliceSelection() {
	currentSlice = null;
	if (isIpad) {
		clickedOnSlice = [0, 0, 0, 0];
	} else {
		// slice color
		if ($.browser.webkit || $.browser.mozilla) {
			$('.slices .slice img.top').each(function () {
				$(this)[0].style.display = "block";
				//$(this).addClass("transparent");
			});
		} else {
			$('.slices .slice img.top').each(function () {
				$(this).css("opacity", "1");
			});
		}
		// badge sliding
		if ($.browser.webkit) {
			$('.slices .slice .badge').each(function () {
				$(this)[0].style.bottom = "-" + sliceBadgeHeight + "px";
				//$(this).css("-webkit-transform", "translate(0, 0px)");
			})
		} else {
			$('.slices .slice .badge').each(function () {
				$(this).css("bottom", "-" + sliceBadgeHeight + "px");
			});
		}
		// bg update (remove)
		$('.bg-image').css({
			"visibility": "hidden",
			"z-index": "1"
		});
	}
}

function updateViewportSettings() {
	var metatags = document.getElementsByTagName('meta');
	for (cnt = 0; cnt < metatags.length; cnt++) {
		var element = metatags[cnt];
		if (element.getAttribute('name') == 'viewport') element.setAttribute('content', 'user-scalable=yes, width=device-width minimum-scale = 1, initial-scale=1, maximum-scale = 5');
	}
}

function overwriteIpadCSS(media, href) {
	var metatags = document.getElementsByTagName('link');
	var found = false;
	for (cnt = 0; cnt < metatags.length; cnt++) {
		if (found) break;
		var element = metatags[cnt];
		if (element.href.indexOf("ipad") != -1) {
			found = true;
			element.type = 'text/css';
			element.rel = 'stylesheet';
			element.href = href;
			element.media = media;
		}
	}
}

function parseClient(str) {
	var r = str;
	if (str == "SouthwestAirlines") r = "Southwest Airlines";
	if (str == "FoxTelevision") r = "Fox Television";
	return r;
}

function setupImageSwapping() {
	var img, sh, sn, sd
	for (var i = 0; i < document.images.length; i++) {
		img = document.images[i]
		if (img.getAttribute && img.n == null) {
			sn = img.getAttribute("src");
			sh = img.getAttribute("hsrc");
			sd = img.getAttribute("dsrc");
			if (sn != "" && sn != null) {
				img.n = new Image();
				img.n.src = img.src;
				if (sh != "" && sh != null) {
					img.h = new Image();
					img.h.src = sh;
					img.onmouseover = imageSwapOn
					img.onmouseout = imageSwapOff
				}
				if (sd != "" && sd != null) {
					img.d = new Image();
					img.d.src = sd;
					img.onmousedown = imageSwapDown
				}
			}
		}
	}
}

function imageSwapOn() {
	this.src = this.h.src;
}

function imageSwapOff() {
	this.src = this.n.src;
}

function imageSwapDown() {
	this.src = this.d.src;
	this.temp = typeof (document.onmouseup) != 'undefined' && typeof (document.onmouseup) != 'unknown' ? document.onmouseup : "";
	imageSwapUp.img = this;
	document.onmouseup = imageSwapUp;
}

function imageSwapUp() {
	var ths = imageSwapUp.img;
	ths.src = ths.n.src;
	if (ths.temp) document.onmouseup = ths.temp;
}

function updateLayout() {
	var w = $('#content').width()
	switch (page) {
	case 'home':
		if (isIpad) {
			//alert(w+' '+mainContentRatio);
			$('.slices').css({
				"width": w + "px",
				"height": Math.floor(w * mainContentRatio) + "px"
			});
		}
		var w2 = $('.slices .slice').width();
		$('.slices .slice img').css({
			"width": w2+ "px",
			"height": Math.floor(w * mainContentRatio) + "px" 	//"auto"
		});
		
		sliceBadgeHeight = $('.slices .slice .badge').height();
		$('.slices .slice .badge').css("bottom", "-" + sliceBadgeHeight + "px");
		break;
	case 'client':
		w = $('#content').width();
		if (isIpad) {
			$('.showcase').css({
				"width": w + "px",
				"height": (w * mainContentRatio) + "px"
			});
		}
		slideWidth = $(".slides").width() - 1;
		slideHeight = $(".slides").height();
		$(".showcase .slides .inside").css({
			"width": slideWidth + "px",
			"height": slideHeight + "px"
		})
		$('.slides .inside .items img').attr({
			width: slideWidth,
			height: slideHeight
		});
		$('.showcase .slides .inside .items').css("margin-left", (0 - slideWidth * currentSlide) + "px").show();
		hash = window.location.hash;
		// select initial slide, if any
		if (hash.length > 0) {
			var slideName = hash.substring(1, hash.length)
			for (i = 0; i < slideNames.length; i++) {
				if (slideNames[i] == slideName) doSlide(i);
			}
		}
		// slides menu initial selection
		toggleMenu(true);
		break;
	}
	if (isIpad) updateFontSize();
	setTimeout(function () {
		scrollTo(0, 1);
	}, 100);

	if (pageWidth == 480) {
		if ($('#content').width() == 480) toggleContent(true);
	} else if (pageWidth == 320) {
		if ($('#content').width() == 320) toggleContent(true);
	} else {
		toggleContent(true);
	}
}

function toggleContent(mode) {
	$(".showcase, .slices, .badge").css("visibility", mode ? "visible" : "hidden");
	if (page == "client") $(".bg-image").css("visibility", "visible");
}

function doSlide(newIndex) {
	if (!slideAnimating) {
		slideAnimating = true;
		toggleMenu(false);
		currentSlide = newIndex;
		window.location.hash = slideNames[currentSlide];
		var v = 0 - slideWidth * currentSlide;
		toggleMenu(true);
/*if ($.browser.webkit) {
$('.showcase .slides .inside .items').css("-webkit-transform", "translate(" + v + "px, 0)");
setTimeout(function () {
slideAnimating = false
}, 500);
} else {*/
		$('.showcase .slides .inside .items').animate({
			marginLeft: v + "px"
		}, {
			duration: 'fast',
			queue: false,
			complete: function () {
				slideAnimating = false;
			}
		}); /*}*/
	}
}

function toggleMenu(mode) {
	var ind = currentSlide + 1;
	var elem = $(".menu div:nth-child(" + ind + ")");
	elem.toggleClass("selected", mode);
}

function changeShare(url, text) {
	fbURL = 'http://www.facebook.com/sharer.php?u=' + url + '&t=' + text;
	twitterURL = 'http://twitter.com/share?url=' + url + '&text=' + text;
}

function goToURL(url) {
	if (!(document.location.href = url)) window.location = url;
}

function openURL(url) {
	window.open(url);
}

function updateFontSize() {
	var winW = document.body.clientWidth || window.innerWidth;
	var prc = (winW / refWidth) * 100;
	if (winW > refWidth) prc = 100;
	document.body.style.fontSize = prc + "%";
}
