var url_cache = {
	// If url is '' (no fragment), display this div's content.
	'': ''
};

var animation_on = false;

jQuery.expr[':'].data = function(elem, index, m) {
 
    m[0] = m[0].replace(/:data\(|\)$/g, '');
 
    var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'),
        key = regex.exec( m[0] )[2],
        val = regex.exec( m[0] )[2];
 
    return val ? jQuery(elem).data(key) == val : !!jQuery(elem).data(key);
 
};


function url_path(url){
	var protocol = url.match('.*:\/\/');
	protocol = (protocol !== undefined && protocol != null)?protocol[0]:'';
	var hash = url.match('^#');
	if(hash === undefined || hash == null || hash =='' ){
		var base, path;
		var base_url = url_base.slice(-(url_base.length-url_base.match('.*:\/\/')[0].length));
		base_url = base_url.replace(/([^\/\?\#]*\.monterosa\.se|monterosa.se|dev.monterosa.se)/gi, 'dev.monterosa.se');
		path = url.slice(-(url.length-protocol.length));
		path = path.replace(/([^\/\?\#]*\.monterosa\.se|monterosa.se|dev.monterosa.se)/gi, 'dev.monterosa.se');
		base = path.match('^' + base_url);
		base = (base !== undefined && base != null)?base[0]:'';
		if(base == '')
			path = url;
		else if(base == base_url){
			path = path.slice(-(path.length-base.length)).replace(/^\/+/, '');
		}
		url = path.replace(/\#.*$/,"");
		return url;
	}	
	url = url.replace(/\#.*$/,"");
	return url;
}
;

var current_path = url_path(location.href);
var last_path = current_path;
var page_titles = {};
var page_menus = {};
var page_content = {};
page_titles[current_path] = document.title;
page_menus[current_path] = $('#menu-main-menu .current-menu-item').attr('id');
var current_header = $('#contentheader .content_header');
var current_page = $('#content .content_main');
if(current_header.length > 0){
	current_header
		.addClass('header-page-' + current_path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
		.addClass('active')					
		.data('page', 'page-'+current_path )
	;	
}else{
	current_header = $('<div/>')
		.data('page', 'page-'+current_path )
		.addClass('content_header')
		.addClass('active')					
		.addClass('header-page-' + current_path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
	;
	$('#contentheader').append(current_header);
}
if(current_page.length > 0){
	current_page
		.addClass('page-' + current_path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
		.addClass('active')					
		.data('page', 'page-'+current_path )
	;	
}else{
	current_page = $('<div/>')
		.data('page', 'page-'+current_path )
		.addClass('content_header')
		.addClass('active')					
		.addClass('page-' + current_path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
	;
	$('#content').append(current_header);
}

function animate_pages_out(delayed){	
	$('html').addClass('animating');
	
	var back_in = function(){
		if(!delayed && ($('#content .content_main.active:hidden').length > 0 || current_path=='cases')){
			delayed = true;
			animate_pages_in();
		}	
	};
	$('#contentheader .content_header:visible').not('.active').each(function(index){
		var offset = -$(this).height() + 'px';	
		if(!animation_on){
			$(this).css(
				{
					'margin-bottom' : '0px'
				}
			).hide();
		}else{
			$(this).animate(
				{ 'top' : offset, 'margin-bottom' : offset }, 
				{ duration: 'slow', complete: function(){
					$(this).css(
					{
						'margin-bottom' : '0px'
					}
					);
					$(this).hide();
				}}
			);
		}
	});
	if(!$('html').is('.ie.lte8')){
		if(!animation_on){
			$('#content .content_main:visible').not('.active').each(function(index){
				var offset = -($(this).height())  + 'px';
				$(this).css(
					{ 'top' : offset, 'margin-bottom' : offset, opacity: 'hide'}
				).hide();
			});
			back_in();
		}else{
			setTimeout(back_in, 500);	
			if(
				!(current_path.match("^cases") == "cases" && current_path != "cases")
				|| last_path == "cases" || !(last_path.match("^cases") == "cases")
				/*				
				&&
				!(last_path.match("^cases") == "cases" && last_path != "cases")
				*/
			){
				//out into top:
				$('#content .content_main:visible').not('.active').each(function(index){
					var offset = -($(this).height())  + 'px';
					$(this).animate(
						{ 'top' : offset, 'margin-bottom' : offset, opacity: 'hide'}, 
						{ duration: 'slow', complete: function(){
							$(this).hide();
						}
						}
					);
				});
			}else{
				//fade it out
				$('#content .content_main:visible').not('.active').each(function(index){
					$(this).animate(
						{ opacity: '0.1'}
					);
				});		
			}
		}
	}else{
		if(!animation_on){
			$('#content .content_main:visible').not('.active').each(function(index){
				var offset = -($(this).height())  + 'px';
				$(this).css(
					{ 'top' : offset, 'margin-bottom' : offset, opacity: 'hide'}
				).hide();
			});	
			back_in();
		}else{
			//out into top:
			setTimeout(back_in, 500);
			$('#content .content_main:visible').not('.active').each(function(index){
				var offset = -($(this).height())  + 'px';
				$(this).animate(
					{ 'top' : offset, 'margin-bottom' : offset}, 
					{ duration: 'slow', complete: function(){
						$(this).hide();
						if(!delayed){
							delayed = true;
							animate_pages_in();
						}
					}
					}
				);
			});
		}		
	}
}

function animate_pages_in(){
	setTimeout(
		function(){
			$('.menu_link_title').removeClass('loading');
			$('html').removeClass('animating');
		}, 400
	);	
		
	$('#contentheader .content_header.active:hidden').each(function(){
		if(!animation_on){
			$(this)
				.css( 
					{ 'top' : '0px', 'margin-bottom' : '0px' } 
				)
				.show();
		}else{
			//in from bottom:
			$(this)
				.css( {
					'top' : - $(this).height() + 'px',
					'margin-bottom' : - $(this).height() + 'px'
				} )
				.show();
			$(this).animate(
				{ 'top' : '0px', 'margin-bottom' : '0px' }, 
				{ duration: 'slow' }
			);
		}
	});
	if(update_sliders !== undefined && update_sliders != null){
		update_sliders();
	}		
	if(!$('html').is('.ie.lte8')){
		if(!animation_on){
			$('#content .content_main.active:hidden').show().css(
				{ 
					'top' : '0px',
					'margin-bottom' : '0px',
					'opacity' : 'show'
				}
			);
			init_sliders();
		}else{	
			if(
				(current_path.match("^cases") == "cases" && current_path != "cases")
				&& (last_path != "cases" && last_path.match("^cases") == "cases")
			){
				//out into top:
				$('#content .content_main:visible').not('.active').hide().css( {'opacity' : '1.0'} );;
				/*
				$('#content .content_main:visible').not('.active').each(function(index){
					var offset = -($(this).height())  + 'px';
					$(this).animate(
						{ 'top' : offset, 'margin-bottom' : offset, opacity: 'hide'}, 
						{ duration: 'slow', complete: function(){
							$(this).hide();
							$(this).css( {'opacity' : '1.0'} );
						}
						}
					);
				});
				*/

				//fade in:
				$('#content .content_main.active:hidden').show().css(
					{ 
						'top' : '0px',
						'margin-bottom' : '0px',
						'opacity' : '0.1'
					}
				).animate({'opacity' : '1.0'});
				init_sliders();
			}else{				
				//in from top:
				$('#content .content_main.active:hidden').show()
					.each(function(){
						$(this)
							.css( {
								'top' : - $(this).height() + 'px',
								'margin-bottom' : - $(this).height() + 'px',
							} );
						init_sliders();
						$(this)
							.hide()
							.animate(
								{ 
									'top' : '0px',
									'margin-bottom' : '0px',
									'opacity' : 'show'
								}, 
								{ duration: Math.round((400+$(this).height())/2) }
							);
					});
			}		
		}
	}else{
		$('#content .content_main.active:hidden').show().css(
			{ 
				'top' : '0px',
				'margin-bottom' : '0px',
				'opacity' : 'show'
			}
		);
		init_sliders();
	}
	var slider = $('#content .anythingslider').data('AnythingSlider');
	if(slider){
		slider.currentPage = 0;
		slider.startStop(true);
	}	
	$('#content .anythingslider').anythingSlider(0);
}

function myajax(targeturl, selector, callback){
	// Default to a GET request
	var type = "GET";
	
	jQuery.ajax({
		url: targeturl,
		type: type,
		cache: false,
		dataType: "html",
		complete: function( res, status ) {
			var self = $('<div/>');
			// If successful, inject the HTML into all the matched elements
			if ( status === "success" || status === "notmodified" ) {
				// See if a selector was specified
				self.html( selector ?
					// Create a dummy div to hold the results
					jQuery("<div>")
						// inject the contents of the document in, removing the scripts
						// to avoid any 'Permission Denied' errors in IE
						.append(res.responseText.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ""))

						// Locate the specified elements
						.find(selector) :

					// If not, just inject the full result
					res.responseText );
					
				if ( callback ) {
					self.each( callback, [res.responseText, status, res] );
				}
			}else{
				var forced404 = "http://dev.monterosa.se/monterosa.se/wp-content/themes/monterosa/forced404.php";
				if(forced404 != targeturl){
					myajax(forced404, selector, callback);
				}else{
					if ( callback ) {
						self.each( callback, [res.responseText, status, res] );
					}
				}
			}
		}
	});
}

function set_path(path){
	if(
		(current_path == "" || path == "")
		//|| ((path.match("^cases")=="cases") && (current_path.match("^cases")=="cases"))
		|| ((path.match("^cases")=="cases") && (current_path == "cases"))
		|| ((current_path.match("^cases")=="cases") && (path == "cases"))
		|| ((current_path.match("^cases")=="cases") && (path.match("^cases")=="cases") && (current_path != "cases"))
	)
		animation_on = true;
	else
		animation_on = false;
	//alert(current_path == 'cases');
	//alert((animation_on?"animate!":"don't animate!") + "\n" + current_path + "\n" + path + "\n\n" + (path.match("^cases")=="cases") + "\n" + (current_path.match("^cases")=="cases"));

	$('#contentheader .content_header.active').removeClass('active');
	$('#content .content_main.active').removeClass('active');

	var delayedanimation = false;

	if(
		$('#contentheader .content_header.header-page-' + path.replace(/[^a-zA-Z0-9\-]+/gi,'_')).length == 0
	){
		delayedanimation = false;
		var offset = -$('#contentheader').height() + 'px';
			//.appendTo("#contentheader");
		if(path != current_path){
			var start = location.href.match(/^.*:\/\/[A-Z0-9\-]*\.?monterosa\.se?/gi);
			var end = url_base.replace(/^.*:\/\/[A-Z0-9\-]*\.?monterosa\.se?/gi,'');
			var targeturl = start + end.replace(/#.*$/,'').replace(/\/*$/,'') + "/" + path;
			targeturl += (targeturl.match(/\?/)?'&':'?') + 'include=true';
			var selector = '#content, #contentfooter, #contentheader, #menu-main-menu, title';
			
			var callback = function(){			
				page_menus[current_path] = $(this).find('#menu-main-menu .current-menu-item').attr('id');
				$('#menu-main-menu .menu-item').removeClass('current-menu-item');
				if(page_menus[path] !== undefined && page_menus[path] != null && page_menus[path] != "" ){
					$('#' + page_menus[path]).addClass('current-menu-item');
				}
				
				var new_title = $(this).find('title').html();
				if(new_title !== undefined && new_title != null && new_title != ''){
					document.title = page_titles[path] = new_title;
				}
				
				var header_element = $(this).find('#contentheader .content_header');
				if(header_element.length > 0){
					$("#contentheader").append(header_element);
					var offset = -header_element.height() + 'px';
					header_element.css({
						 'top' : offset, 'margin-bottom' : offset
					}).hide();
				}else{
					$("#contentheader").append(header_element = $('<div/>'));
				}
				header_element
					.data('page', 'page-'+path )
					.addClass('content_header')
					.addClass('active')					
					.addClass('header-page-' + path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
					.hide()
				;		
				
				var main_element = $(this).find('#content .content_main');
				if(main_element.length > 0){
					var cases = $('#content .content_main.page-cases');
					if(cases.length > 0)
						cases.before(main_element);
					else
						$("#content").append(main_element);
					var offset = $('body').height() + 'px';
					main_element.css({
						 'top' : offset
					}).hide();
				}else{
					$("#content").append(main_element = $('<div/>'));
				}
				main_element
					.data('page', 'page-'+path )
					.addClass('content_header')
					.addClass('active')					
					.addClass('page-' + path.replace(/[^a-zA-Z0-9\-]+/gi,'_'))
					.hide()
				;
				
				animate_pages_in();
			};

			myajax(targeturl, selector, callback);
		}
	}else{
 		if(page_titles[path] !== undefined && page_titles[path] != null && page_titles[path] != ''){
			document.title = page_titles[path];
		}
		$('#menu-main-menu .menu-item').removeClass('current-menu-item');
		if(page_menus[path] !== undefined && page_menus[path] != null && page_menus[path] != '')
			$('#' + page_menus[path]).addClass('current-menu-item');
	}
	
	if(path.match("^cases")=="cases" && current_path.match("^cases")=="cases"){
		$('#content .content_main.page-cases').addClass('active');
	}

	last_path = current_path;
	current_path = path;
	
	var pageid = path.replace(/[^a-zA-Z0-9\-]+/gi,'_');
	$('#contentheader .content_header.header-page-' + pageid).addClass('active');
	$('#content .content_main.page-' + pageid).addClass('active');

	animate_pages_out(delayedanimation);
	
	/*
	if(!delayedanimation){
		animate_pages_in();
	}
	*/
	
	if(update_sliders !== undefined && update_sliders != null){
		update_sliders();
	}
}

set_path( current_path );

$(/*'#access li a, .header a'*/ 'a').live('click', function() {
	var href = $(this).attr('href');
	if(href.match("^mailto")=="mailto")
		return true;
	var path = url_path(href);
	var protocol = path.match('.*:\/\/');
	var hash = path.match('^#');
	if(
		(protocol === undefined || protocol == null) &&
		(hash === undefined || hash == null)
	){
			//.slideUp();
		location.href = '#/' + path;
		this.blur();
		return false;
	}
});	




$(function(){
	$(window).bind( 'hashchange', function(e) {   
		var fragment, path;
		if(window.location.hash.match(/\#/)){
			fragment = window.location.hash.replace(/^\#*\/*/,'');
			var links = $('a[href$="\/' + fragment +'\"]');
			if(links.length){
				path = url_path(links.first().attr('href'));
			}else{
				var anchor = $('.content_main.active a[name="' + fragment + '"]');
				if(anchor.length > 0){
					if(anchor[0].scrollIntoView){
						anchor[0].scrollIntoView();
						return false;
					}
				}else
					path = url_base + "/" + fragment;
			}
		}else{
			path = current_path;
		}
		if(path != current_path){

			// Anton: Check if path or current_path is a case. If so, skip the animation to avoid problems with youtube etc
			if ((path.length > 6 && path.substring(0,6) == "cases/") || (current_path.length > 6 && current_path.substring(0,6) == "cases/")) {

			window.location.href = url_base + '/' + path;
			return false;
}

			if((path.match("^cases")=="cases")){		
				$('a[href$="\/cases\"]').parent().filter('.menu_link_title').addClass('loading');
			}else{
				$('a[href$="\/' + fragment +'\"]').parent().filter('.menu_link_title').addClass('loading');			
			}

			//path is the path of the clicked link, current_path is the path of the currently displayed page
			//to do a hard link, instead of loading content dynamically, use the following instead of set_path():
			//window.location.href = url_base + '/' + path;
//alert(url_base);
//alert(path);

			set_path(path);
			if ( url_cache[ fragment ] ) {
			  
			}

		}
		//}
		
		return false;
	})
  
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );
  
});

jQuery('document').ready(function(){
	$('a').click(function(){
		if (jQuery(this).attr('rel') != 'home' && jQuery(this).attr('rel') != 'mail')
			{
				$('.awards').css('display','none');
				$('.brands').css('display','none');
			}
		else
			{
				$('.awards').fadeIn(300);
				$('.brands').fadeIn(300);
			}
	});
	if (top.location.href.match('cases') == true || top.location.href.match('who') == true || top.location.href.match('contact') == true)
		{
			$('.awards').css('display','none');
			$('.brands').css('display','none');
		}
	else
		{
				$('.awards').fadeIn(300);
				$('.brands').fadeIn(300);
		}
});

