animating = false

Element.addMethods({
  scrollTo: function(element, left, top){
    var element = $(element);
    if (arguments.length == 1){
      var pos = element.cumulativeOffset();
      window.scrollTo(pos[0], pos[1]);
    } else {
      element.scrollLeft = left;
      element.scrollTop  = top;
    }
    return element;
  }
});
Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    this.start(Object.extend({x: 0, y: 0}, arguments[1] || {}));
  },
  setup: function() {
    var scrollOffsets = (this.element == window) 
                ? document.viewport.getScrollOffsets() 
                : Element._returnOffset(this.element.scrollLeft, this.element.scrollTop) ;
    this.originalScrollLeft = scrollOffsets.left;
    this.originalScrollTop  = scrollOffsets.top;
  },
  update: function(pos) {
    this.element.scrollTo(Math.round(this.options.x * pos + this.originalScrollLeft), Math.round(this.options.y * pos + this.originalScrollTop));
  }
});

function append_load_div_to_content() {
	loader_div = '<div id="loaded"><img src="/images/contact.jpg" alt="" class="background"><div class="content"><div class="background"></div></div></div>'
	$('main').insert(loader_div)
	$('loaded').style.left = '945px'
}

function fix_ie_nav_items() {
	// This inserts little white boxes with the background image
	// behind nav items so they remain clickable but still show the nice transparent background
	if (Prototype.Browser.IE) {
		$$('#navmenu>li').each(function(e){
			insert = 'display:block; height:49px; width:189px; position:absolute; left:0; top:0; z-index:1; '
			switch (e.id) {
				case 'nav-residences':
				case 'nav-coachella':
				case 'nav-life':
				case 'nav-spa':
				case 'nav-dining':
					insert += 'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/stylesheets/images/nav-top.png\',sizingMethod=\'scale\');'
					break
				default:
					insert += 'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/stylesheets/images/nav-bottom.png\',sizingMethod=\'scale\');'
			}
			e.style.background = 'none'
			e.insert('<div class="IEBACKGROUND" style="' + insert + '">&nbsp;</div>','bottom')
		})
	}
}

function trap_clicks() {
	$$('#navmenu a').each(function(e) {
		Event.observe(e, 'click', link_clicked)
	})
}

function link_clicked(e) {
	if (animating != true) {
		link_target = strip_server(this.href)
		if (link_target.endsWith(".pdf") || link_target.startsWith("http://")) {
			(link_target == 'http://rcm.colin.dev/') ? window.location = link_target : window.open(link_target)
		} else {
			ajax_load_page(link_target)
		}
	}
	Event.stop(e)
	return false
}

function ajax_load_page(uri) {
	link_target = uri
	if (uri.endsWith("/")) {
		if (uri == '/') {
			link_target = '/index'
		} else {
			link_target = uri + uri.split("/").uniq().last()
		}
	}
	urchinTracker(uri)
	link_target = '/content' + link_target + '.mangler'
	new Ajax.Request(link_target, {method:'get', onSuccess:loaded_page})	
}

function loaded_page(r) {
	text = r.responseText
	body = text.split("\n---------- Body ----------\n")[1]
	image = ''
	position = ''
	text.split("\n---------- Body ----------\n")[0].split("\n").each(function(e){
		if (e.startsWith("image: ")) image = e.split("image: ")[1]
		if (e.startsWith("position: ")) position = e.split("position: ")[1]

	})
	animate_content(image, position, body)
}

function animate_content(image, position, body) {
	animating = true
	var visible = $('visible')
	var loaded = $('loaded')
	var loaded_content = $$('#loaded .content').first()
	var visible_content = $$('#visible .content').first()
	var p = $A(['nil', 'one', 'two', 'three', 'four', 'five']).indexOf(position.split(" ")[0])
	var c = $A(['nil', 'one', 'two', 'three', 'four', 'five']).indexOf($$('body').first().className.split(" ")[0])
	
	loaded_content.innerHTML = '<div class="background"></div>' + body
	$$('#loaded img.background').first().src = '/images/' + image + '.jpg'

	$$('#navmenu ul').each(function(i){	new Effect.Morph(i, {style:'opacity:0', duration:0.3, delay:0, queue:'shrink'}) }) // Hide sub-nav

	new Effect.MoveBy('head', 0, ((p - c) * 189), { duration:0.5, delay:0.4, queue: 'shrink'})

	// MOVE LOGO
	am_up = ($$('body').first().className.split(" ").indexOf('up') >= 0)
	going_up = (position.indexOf('up') >= 0)
	if (am_up != going_up)	{new Effect.MoveBy($$('#head h1 a').first(), going_up ? 195 : -195, 0, {duration:0.3, delay:0.5})}
	// TOGGLE ADDRESS
	if ((image == 'contact') || (image == 'buzz')) {
		if ($$('body').first().hasClassName('contact') == false)
			new Effect.Fade('addressblock', {duration:0.5, delay:0.9, from:0.01, to:1, queue:'shrink'})
	} else {
		if (($$('body').first().hasClassName('contact')) || ($$('body').first().hasClassName('buzz')))
			new Effect.Fade('addressblock', {duration:0.5, delay:0, from:1, to:0.01, queue:'shrink'})
	}

	loaded.style.left = '945px'
	loaded_content.style.top = '479px'
	visible.style.left = '0'
	visible_content.style.top = '0'
	
	new Effect.MoveBy(visible_content, 479, 0, { delay:0, duration:0.5, queue:'shrink'})		
	new Effect.MoveBy(loaded, 0, -945, { delay:0.8, duration:0.5, queue:'shrink'})		
	new Effect.MoveBy(visible, 0, -945, { delay:0.8, duration:0.5, queue:'shrink'})		
	new Effect.MoveBy(loaded_content, -479, 0, { delay:1.1, duration:0.5, queue:'shrink'})		

	setTimeout(function(){
		$$('body').first().className = position + ' ' + image
		p = (image == 'map') ? 3 : $A(['nil', 'one', 'two', 'three', 'four', 'five']).indexOf(position.split(" ")[0])
		new_position = $A(['0', '189px', '378px', '0', '190px', '378px'])[p]
		loaded_content.style.left = new_position;
		visible_content.style.left = loaded_content.style.left;
	}, 1000)
	$$('#navmenu ul').each(function(i){	new Effect.Morph(i, {style:'opacity:1', duration:0.3, delay:2, queue:'shrink'}) }) // Show sub-nav
	setTimeout(function(){ reset_content_blocks(image, position, body) }, 2000)

}

function reset_content_blocks(image, position, body) {
	$$('#visible .content').first().innerHTML = '<div class="background"></div>' + body
	$$('#visible img.background').first().src = '/images/' + image + '.jpg'
	$$('#visible .content').first().style.top = '0'
	$$('#loaded .content').first().style.top = '479px'
	$('visible').style.left = '0'
	$('loaded').style.left = '945px'
	animating = false
}

function strip_server(uri) {
	new_uri = uri
	Array(
		'http://constellationcollection.com',
		'http://www.constellationcollection.com',
		'http://livingranchomirage.com',
		'http://ownranchomirage.com',
		'http://www.ownranchomirage.com',
		'http://www.livingranchomirage.com',
		'http://lrm.colin.dev',
		'http://lrm.appliedinteractive.ca'
	).each(function(u) {
		new_uri = new_uri.sub(u,'')
	})
	return new_uri
}

function init() {
	append_load_div_to_content()
	fix_ie_nav_items()
	trap_clicks()
}

document.observe("dom:loaded", init, false)
