var console;
if (console == undefined) {
	console = { log: function() {} };
}

var Site = function() {
	// SETUP
	
	var firstHover = true;
	var hasHash = false;
	var currentSection = 0;
	var currentStrip = -1;
	var currentStripOpenCount = 0;
	var colWidth = 0;
	var colGroup = 0;
	var opening = false;
	var windowWidth;
	var windowHeight;
	var ratioOver = 1;
	var ratioUnder = 1;
	var user;
	var loginURL;
	var attachedContentFrameLoadHandler;
	var activatedGuestPass = ($.cookie('membersloungeguestpass') == "yessir");
	
	/*
	** Adding a new section here will make the framework accept the new section "/#/sectionName"
	** Although, if there is not a "strip" for this section on the ./index.php (look for <div id="strips">)
	** the content of the new section won't be loaded. You may be able to see the specified background.
	*/
	var sections = [
		{ name: "", bg: "img/bg/start.jpg" },
		{ name: "latest", bg: "img/bg/latest.jpg" },
		{ name: "music", bg: "img/bg/music.jpg" },
		{ name: "sharpen", bg: "img/bg/sharpen.jpg" },
		{ name: "see", bg: "img/bg/see.jpg" },
		{ name: "places", bg: "img/bg/places.jpg" },
		{ name: "offers", bg: "img/bg/offers.jpg" },
		{ name: "members", bg: "img/bg/start.jpg", dontAnimate:true },
		{ name: "preview", bg: "img/bg/places.jpg" },
    { name: "surprisegig", bg: "img/bg/surprisegig.jpg" },
		{ name: "splendourinthegrass", bg: "img/bg/splendour.jpg" }
	];
	
	function resetSizes(){
		windowWidth = $(window).width();
		windowHeight = $(window).height();
		colWidth = Math.round(windowWidth/6);
		colGroup = colWidth*6;
	}
	
	function imgWindowRatio(){
		var $background = $('#scale img');
		
		var imgWidth = $background.width();
		var imgHeight = $background.height();
		ratioOver = imgWidth / imgHeight;
		ratioUnder = imgHeight / imgWidth;
		
		if((windowWidth / windowHeight) >= ratioOver) {
			return 'taller';
		} else {
			return 'wider';
		}
	}
	
	function scaleBackground(){
		var $background = $('#scale img');
		if(imgWindowRatio() == 'taller'){
			$background.css('width',windowWidth);
			$background.css('height',Math.floor(ratioUnder*windowWidth));
		} else {
			$background.css('width',Math.floor(ratioOver*windowHeight));
			$background.css('height',windowHeight);
		}
	}
	
	function resizeCols(section){
		if (!opening)
			$('div.strip').stop().hide().css('width', colWidth-2+'px');
		
		if(section){
			var $cols = $('div.strip'+section);
			var $colImageStrips = $('div.strip'+section+' .strip-img');
			var $colImages = $('div.strip'+section+' .strip-img img');
		} else {
			var $cols = $('div.strip');
			var $colImageStrips = $('div.strip .strip-img');
			var $colImages = $('div.strip-img img');
		}
		
		$colImageStrips.css('width',windowWidth);
		$colImageStrips.css('height',windowHeight);
		
		if(imgWindowRatio() == 'taller') {
			$colImages.css('width',windowWidth);
			$colImages.css('height',Math.floor(ratioUnder*windowWidth));
		} else {
			$colImages.css('width',Math.floor(ratioOver*windowHeight));
			$colImages.css('height',windowHeight);
		}
		
		$colImages.each(function(index){
			$(this).css('left', '-'+colWidth*index+'px');
		});
		
		$cols.each(function(index){
			$(this).css('left', colWidth*index+'px');
		});
		
		var $colNav = $('div.stripnav');

		$colNav.each(function(index){
			$(this).css('left', colWidth*index+'px').css('width', colWidth);
		});
	}
		
	
	// FUNCTIONS FOR IMAGES SCALING AND NAVIGATION
	
	function resizeElements(trigger){
		resetSizes();
		
		if(trigger != 'resize'){
			setBackground(currentSection);
		}
		
		scaleBackground();
		resizeCols();
		resetNav();
	}
	
	function setBackground(section){
		// check if new background image has loaded yet		
		var $bgImage = $('#scale img.bg');
		var $newBg = $bgImage.clone().attr('src', sections[section].bg);

		$newBg.appendTo('#scale').show();
		$bgImage.hide().remove();
	}
	
	function resetNav(){
		var navOffset = windowWidth-colGroup;
		var $navItems = $('#nav li');
		$navItems.css('width', colWidth);
		
		if(navOffset > 0){
			$($navItems.get($navItems.length - 1)).css('width', colWidth+navOffset);
		}
		$navItems.each(function(index){
			$(this).css('left', colWidth*index+'px');
		});
	}
	
	var stripCloseTimeout = null;
	
	function stripOpen(section){
		if(firstHover){
			resizeCols();
			firstHover = false;
		}
		
		if (stripCloseTimeout != null) {
			clearTimeout(stripCloseTimeout);
			stripCloseTimeout = null;
			
			if (section != currentStrip)
				stripClose(currentStrip);
		}
		
		if(currentSection != section || currentSection == 0){
			
			if(!opening){
				if (section == currentStrip) {
					currentStripOpenCount++;
					return;
				}
				currentStrip = section;
				currentStripOpenCount = 1;
				
				var $newCol = $('div.strip'+section);
				var $imgCol = $('div.strip'+section+' img');

				$('div.strip').hide();
				$('#strips').show();
				$newCol.show();
				var colPos = $newCol.position();
				var colLeft = Math.floor(colPos.left);
				var startOffset = Math.floor(colLeft + (colWidth/2));
				$newCol.width('0');

				$newCol.css('left', startOffset+'px');
				$imgCol.css('left', '-'+startOffset+'px');

				var imgColStart = -startOffset;
				var imgColEnd = -colLeft;
				$newCol.animate({ width: colWidth + (jQuery.support.boxModel ? -1 : 1), left: colLeft},
						{ duration: 400, easing: "easeOutQuad", step: function(now, state) {
					if (state.prop == "width") {
						var r = state.now / (state.end - state.start);
						var imgColNow = r * (imgColEnd - imgColStart) + imgColStart;
						$imgCol.css('left', imgColNow + "px");
					}
				} });
			
				if(currentSection == 0){
					// can remove this if decision is to keep rollover text at all times
					$('#stripnav em').removeClass('active');
					$('#stripnav div.stripnav'+section+' em').addClass('active');
				} else {
					$('#stripnav em').removeClass('active');
					$('#stripnav div.stripnav'+section+' em').addClass('active');
					$('#stripnav .stripnav').hide();
					$('#stripnav .stripnav'+section).show();
					$('#stripnav').show();
				}
			
			}
			
		}
		
	}
	
	function stripClose(section) {
		if (section == currentStrip && section != -1)
			if (currentStripOpenCount > 0)
				return;
		
		currentStrip = -1;
		currentStripOpenCount = 0;

		if(currentSection != 0){
			$('#stripnav').hide();
		} else {
			$('#stripnav').show();
		}
		resizeCols();
		$('#strips').hide();
		$('#stripnav em').removeClass('active');
	}
	
	function stripCloseDelay(section) {
		if (section == currentStrip) {
			currentStripOpenCount--;
			clearTimeout(stripCloseTimeout);
			stripCloseTimeout = setTimeout(function() {
				stripClose(section);
			}, 500);
		}
	}
	
	function revealPage(section, url){
		if(currentSection != section){
			opening = true;
			
			if($.browser.msie){
				$('#stripnav').hide(); // because IE7 botches fades on transparent PNGs
			} else {
				$('#stripnav').fadeOut(function(){
					$(this).hide();
				});				
			}
			
			if(section != 0){
				$('#stripnav').addClass('inside');
			} else {
				$('#stripnav').removeClass('inside');
			}
			
			if(sections[section].dontAnimate != null){
				// members section, so don't animate
				$('#content').hide();
				currentSection = section;
				resizeElements(section);
				if(url != null){
					loadContent(url, section);
				}
				$('#strips').hide();
				opening = false;
				return;
			}
			
			var $newCol = $('div.strip'+section);
			
			// is it a valid section?
			if ($newCol.length == 0){
				$('#content').hide();
				currentSection = section;
				resizeElements(section);
				stripClose();
				opening = false;
				return;
			}
			
			var $imgCol = $('div.strip'+section+' img');
	
			$newCol.show();
			var colPos = $newCol.position();
			var startOffset = colPos.left;
	
			$newCol.css('left', startOffset+'px');
			$imgCol.css('left', '-'+startOffset+'px');
	
			$imgCol.animate({ left: 0 }, 500);
			
			function newColOpened() {
				$('#content').hide();
				currentSection = section;
				resizeElements(section);
				if(url != null){
					loadContent(url, section);
				}
				$('#strips').hide();
				opening = false;
			}
			
			if (sections[section].loaded)
				$newCol.animate({ width: windowWidth, left: -1}, 500, newColOpened);
			else
				newColOpened();
		} else {
			if (url != null)
				loadContent(url, section);
		}
	}

	// MAIN CONTENT AREA
	
	function loadContent(url, section){
		if (url == "")
			return;
		
		var $contentArea = $('#content');
		$('#nav').show();
		
		if (!attachedContentFrameLoadHandler) {
			attachedContentFrameLoadHandler = true;
			$('#content-frame').load(function(){
				var $contentBody = $('#content-frame').contents().find('body');
				
				if( $contentBody.height() > windowHeight ){
					$('#content').addClass('scrollable');
				} else {
					$('#content').removeClass('scrollable');
				}
				
				if($.browser.msie){
					$('#content-frame').contents().find("body").attr('scroll', 'no');
				}
				
				$('#page-loader').removeClass('page-loading');
				
				function contentAreaDone() {
					$contentArea.css('padding-top', '0px');
					$('#content-frame').attr('scrolling', 'auto');
					$('#content-frame').css('overflow', 'auto');
					$('#content').removeClass('scrollable');
	
					if($.browser.msie){
						$('#content-frame').contents().find("body").attr('scroll', 'auto');
					} else if($.browser.safari || $.browser.opera){
						$('#content-frame').contents().find("body").css('overflow', 'auto');
					}
				}
				
				if ($.browser.mozilla && navigator.platform == "Win32")
					/* Mozilla on Windows can't handle the power of our animation */
					contentAreaDone();
				else
					$contentArea.animate({ paddingTop: 0 }, 1000, contentAreaDone);
			}).error(function(){
				alert('failed to load');
			});
		}
					
		$contentArea.stop().css('padding-top', windowHeight);
		$contentArea.show();
		$('#page-loader').addClass('page-loading');
		$('#content-frame').attr('scrolling', 'no').css('overflow', 'hidden');
		if (url.charAt(0) != '/')
			url = cp + "/" + url;
		$('#content-frame').contents()[0].location.replace(url);
		
		$('#nav li').removeClass('selected');
		$('#nav li.nav'+section).addClass('selected');
	}
	
	$('a[rel="popup"]').click(function(){
		var link = $(this).attr('href');
		day = new Date();
		id = day.getTime();
		window.open(link,id,'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=650');
		return false;
	});
	
	// IMAGE LOADING
	
	function loadBackgroundImages() {
		for (var i = 1; i < sections.length; i++) {
			loadBackgroundImage(i);
		}
	}
	
	function loadBackgroundImage(num) {
		if (sections[num].loading)
			return;
		sections[num].loading = true;
		
		var img = new Image();
		$(img).load(function(){
			$('div.strip'+num+' .strip-img').html(this).append('<div class="overlay"></div>');
			resizeCols(num);
			sections[num].loaded = true;
		}).error(function(){
			// image couldn't be loaded
		}).attr('src', sections[num].bg);
	}


	// LET'S GET THE PARTY STARTED
	
	function refigure(trigger){
		resizeElements(trigger);
		if($.browser.mozilla){
			setTimeout(function() {
				resizeElements(trigger);
			}, 50);
		}
	}
	
	function findSectionIndexByName(name) {
		for (var i = 0; i < sections.length; i++)
			if (sections[i].name == name)
				return i;
		return -1;
	}
	
	function navigationLoad(hash) {
		var parts = hash.replace(/^\/?(.*?)\/?$/, "$1").split('/');
		
		var sectionName = parts[0];
		var section = findSectionIndexByName(sectionName);
		
		if (parts.length > 0)
			goPage(section, hash.replace(/^\//, ""));
	}
	
	function goPage(section, page) {
		if (sections[section] == undefined)
			return;
		
		if (!sections[section].loaded) {
			loadBackgroundImage(section);
			setTimeout(function() {
				goPage(section, page);
			}, 100);
			return;
		}
		
		revealPage(section, page);
	}
	
	function initHashNavigation() {
		$.historyInit(navigationLoad, "iehistory.html");
	}
	
	function setSectionFromContent(sectionName) {
		var section = findSectionIndexByName(sectionName);
		if (currentSection != section)
			setBackground(section);
	}
	
	function setContentFromContent(url) {
		$.historyLoad(url);
	}
	
	function userLoggedIn(aUser, reload) {
		if (reload === true) {
			location.href = location.protocol + "//" + location.host + "" + location.hash.substr(1);
		} else {
			user = aUser;
			
			closeLoginPanel();
			$("#login-button").hide();
			$("#logout-button").show();
			
			$('#nav, #stripnav').fadeIn();
			
			
			var messages = [
				"Hi <name>, glad you could join us.",
				"Hey <name>, nice to see you back.",
				"So <name>, what're you in the mood for today?",
				"Hey everyone, <name> is here!",
				"Perfect timing <name>. Check out what's new."
			];
			
			var welcome = messages[Math.floor(Math.random()*messages.length)];
			welcome = welcome.replace('<name>', user.firstName);
			
			$('#message p').html(welcome);

			Cufon.refresh('#message p');
			
			$('#twitter').hide();
			$('#welcome').show();
			showTwitter();
		}
		
	
		
//		user.serviceNum;
//		user.firstName;
//		user.lastName;
//		user.accountType;
//		user.email;

	}
	
	function userLoginFailed() {
//		alert("User login failed");
	}
	
	function userLogout() {
		user = null;
		
		$("#logout-button").hide();
		$("#login-button").show();
		
		// Tell the server we've logged out
		location = cp + "/login/logout.php";
	}
	
	function userIsLoggedIn() {
		return user != null;
	}
	
	function closeLoginPanel(){
		if( $('#login-slider').is(':visible') ){
			$("#login-options, #login-form").hide();
			$("#shade").animate({ opacity: 0 }, 300).hide();
			slideLoginPanel(27);
			$(this).delay(510, function() {
				$("#login-header").show();
				$("#login-header-open").hide();
			});
		}
	}
	
	// LOGIN PANEL

	function slideLoginPanel(h) {
		if (h == null) h = 20;
		var contentHeight = $("#login-slider div.content-wrap:visible").height();
		$("#login-slider").animate({ height: contentHeight+h+"px" }, 500, false, function() {
			if (!contentHeight) {
				$("#login-slider").hide();
			}
		});
	}

	
	// TWITTER
	function showTwitter(){
		if ($('#twitter-list .twitter-status').length == 0) {
			setTimeout(showTwitter, 1000);
			return;
		}
		
		Cufon.refresh('#twitter-list li span');
		
		$("#twitter").show();
		$("#twitter-list").show();
		var firstTweetHeight = $("#twitter-list li:first-child").height();
		var twitterPanelHeight = $("#twitter-panel").height();
		$("#twitter-mask").height(firstTweetHeight+8);
		$("#twitter-bg-mask").height(firstTweetHeight);
		$("#twitter").height($("#twitter-mask").height());
		
		Cufon.refresh('#twitter-list li span');
				
		$("#twitter-reveal").toggle(function() {
			$("#twitter-mask").animate({height: twitterPanelHeight}, "fast");
			$("#twitter-bg-mask").animate({height: twitterPanelHeight-5}, "fast");
		}, function() {
			$("#twitter-mask").animate({height: firstTweetHeight+8}, "fast");
			$("#twitter-bg-mask").animate({height: firstTweetHeight}, "fast");
		});
	}
	
	function showLoginPanel(){
		$("#login-button").hide();
		$("#shade").show().css('opacity', 0).animate({ opacity: 0.8 }, 300);
		$("#login-header").hide();
		$("#login-header-open").show();
		$("#login-slider").show();
		$('#login-options').show().animate({opacity: 0}, 0);
		$("#login-button").delay(500, function(){
			$('#login-options').animate({opacity: 1}, 1000);
		});
		slideLoginPanel();
	}
	
	function isAllowedToNavigate() {
		return userIsLoggedIn() || activatedGuestPass;
	}

	function initLogin() {

		$("#login-mlogin").click(function(e) {
			$("#login-options").hide();
			$("#login-form").show();
			$('#login-form iframe').attr("src", loginURL);
			slideLoginPanel();
			e.preventDefault();
		});

		$("#login-guest").click(function(e) {
			closeLoginPanel();
			$(this).delay(1010, function() {
				$("#login-button").show();
			});
			e.preventDefault();
			$.historyLoad("/" + $(this).attr('href'));
			$.cookie("membersloungeguestpass", "yessir", { expires: 31 });
		});

		$('#shade').click(function(e){
			if (isAllowedToNavigate()) {
				closeLoginPanel();
				$(this).delay(1010, function() {
					$("#login-button").show();
				});
			}
			e.preventDefault();
		});
		
		
		$("#login-button").click(function(e) {
			showLoginPanel();
			e.preventDefault();
		});

		$("#logout-button").click(function(e) {
			userLogout();
			e.preventDefault();
		});
		
		loginURL = $('#login-form iframe').attr('src');
	}
	
	function initNav() {
		$('#stripnav a').hover(
			function(){
				if(!opening){
					stripOpen( $(this).attr('rel') );
				}
			},
			function(){
				if(!opening){
					stripCloseDelay( $(this).attr('rel') );
				}
			}
		);
		
		$('#stripnav a').click(
			function(){
				var section = $(this).attr('rel');
				$.historyLoad("/" + $(this).attr('href'));
				return false;
			}
		);
		
		
		$('#nav a').hoverIntent(
			function(){
				if(!opening){
					stripOpen( $(this).attr('rel') );
				}
			},
			function(){
				if(!opening){
					stripCloseDelay( $(this).attr('rel') );
				}
			}
		);

		$('#nav a').click(
			function(){
				if(!opening){
					$.historyLoad("/" + $(this).attr('href'));
				}
				return false;
			}
		);
	}
	
	function init() {
		windowWidth = $(window).width();
		windowHeight = $(window).height();
		
		$('#strips').hide();
		
		if($.browser.msie){
			$('#loader').append('<div class="loader-ani"></div>');
		}
		
		// SET UP INTERACTION HOOKS FOR NAV
		
		initLogin();
		initNav();
		initHashNavigation();
		
		// GENERAL
		
		$(window).load(function() {
			
		});
		
		$(window).resize(function(){
			refigure('resize');
		});
		
		// Once initial background image is loaded, show content
		$('img.bg').onImagesLoad({ selectorCallback: function(){
			$('#page-loader').hide();
			$('#footer, #header').show();

// This comments was done due to the surprisegig campaign
// It disable the compulsory login banner
// The user has to click on the login button to see the component that would scroll automatically
// After the campaign uncoment the following line.
//			if (userIsLoggedIn() || activatedGuestPass) {
				$('#nav, #stripnav').show();
//			} else {
//				showLoginPanel();
//			}

			refigure();
			sections[0].loaded = true;
			loadBackgroundImages();
		}});
	}
		
	// PUBLIC API
	return {
		init: init,
		setSection: setSectionFromContent,
		setContent: setContentFromContent,
		login: userLoggedIn,
		loginFailed: userLoginFailed,
		logout: userLogout,
		isLoggedIn: userIsLoggedIn,
		showLoginPanel: showLoginPanel
	};
}();
	
$(function() {
	Site.init();
});
