/*
 * Variables
 *
 */

var total_items= 0;
var total_scroll= 0;
var current_item= 0;

var contentWidth= 0;

var speed= 800;
var numscroll= 0;

var timer= 0;

var go= true;
var dist= 0;
var scrollbar;
var handleHelper;
var scrolling= false;

var activeCategories= new Array();
var servicesActive= false;

/*
 * Utility Functions and Element Setters
 *
 */

function newsletter()
{
	window.open("http://www.gmtn.dk/sign-up/newsletter/index.php", "Newsletter", "width=400,height=250,scrollbars=yes,directories=no,top=200,left=300"); 
}

Array.prototype.remove= function(s)
{
  for( i=0; i<this .length; i++ )
  {
    if ( s == this[i] )
    	this.splice( i, 1 );
  }
}

function calcItems()
{
	total_items= jQuery("#Content ul li.top").size() - 1;

	contentWidth= 0;	
	jQuery("#Content ul li.top").each(
		function()
		{
			contentWidth+= jQuery(this).outerWidth();
		}
	);
	
	if ( jQuery("#Content ul li").size() <= 1 )
	{
		jQuery(".ui-slider-handle").hide();
	}
	else
	{
		jQuery(".ui-slider-handle").show();
	}
}

function workHover()
{
	jQuery(".type_4 .item").hover(
		function()
		{
			jQuery(".cover:animated").stop().animate( { "opacity": 0 } , 10);
			jQuery(this).find(".cover").fadeTo(250, 1.0);
		},
		function()
		{
			jQuery(this).find(".cover").animate( { "opacity": 0 } , 250);
		}
	)
}

function updateScrollbarMax()
{
	jQuery("#Content").scrollLeft(0);
	jQuery("#Handle").slider('option', 'value', 0);
	jQuery("#Handle").slider( "option", "max", jQuery("#Content ul li.top:last-child").position().left );
}

function setScrollBar()
{	
	var scrollPane		= jQuery("#ScrollBar");
	var scrollContent	= jQuery("#Content ul");
	var introWidth		= jQuery("#Intro").width();
	
	scrollbar = jQuery("#Handle").slider(
	{
		animate	: 	true,
		min		: 	0,
		max		: 	jQuery("#Content ul li.top:last-child").position().left,
		slide	: 	function(e, ui)
					{
						jQuery("#Content").stop();
						jQuery("#Content").animate( {scrollLeft: ui.value}, speed);
					}
	});
		
	handleHelper= scrollbar.find('.ui-slider-handle').wrap('<div class="ui-handle-helper-parent"></div>').parent();
		
	function sizeScrollBar()
	{
		var handleSize = 200;
		scrollbar.find(".ui-slider-handle").css(
		{
			"width"			: 	handleSize,
			"margin-left"	: 	-handleSize/2
		});
		
		handleHelper.width("").width( scrollbar.width() - handleSize);
	}
		
	jQuery(window).resize(
		function()
		{
			jQuery("#ScrollBarWrapper").width( jQuery(window).width() - introWidth );
			jQuery(".ui-handle-helper-parent").width( jQuery("#ScrollBarWrapper").width() - 200 );
			sizeScrollBar();
		}
	);
		
	jQuery("#ScrollBarWrapper").width( jQuery(window).width() - introWidth );
	jQuery(".ui-handle-helper-parent").width( jQuery("#ScrollBarWrapper").width() - 200 );
	
	setTimeout( sizeScrollBar, 10 );
	
	if ( jQuery("#Content ul li.top").size() <= 1 )
	{
		jQuery(".ui-slider-handle").hide();
	}
	else
	{
		jQuery(".ui-slider-handle").show();
	}
	
	jQuery("#Handle").slider('option', 'value', jQuery("#Content").scrollLeft() );
}

function scrollIt( howmuch, dir )
{
	scrolling= true;
	numscroll= 0;
	if ( dir == 1 )
	{
		total_scroll= current_item + howmuch;
		if ( total_scroll > total_items)
        	total_scroll= total_items;
		
 		var target= jQuery("#Content ul li.top:eq(" + total_scroll + ")").position().left;
 		current_item= total_scroll;
          	
 		go= false;
 		if ( dist == 1 )
          dist *= 2;
          
      	jQuery("#Content").animate( { scrollLeft: jQuery("#Content").scrollLeft() + target }, dist * speed,
      		function()
      		{
      			go= true;
      			numscroll= 0;
      			scrolling= false;
      			
      			clearTimeout(timer);
      		}
  		);
  		
  		
  	}
  	else if ( dir == 0 )
  	{
  		total_scroll= current_item - howmuch;
 		if ( total_scroll < 0)
          total_scroll= 0;

 		var target= $("#Content ul li.top:eq(" + total_scroll + ")").position().left;
 		current_item= total_scroll;
          	
 		go= false;
 		if ( dist == 1 )
          dist *= 2;
      		jQuery("#Content").animate( { scrollLeft: jQuery("#Content").scrollLeft() + target }, dist * speed,
      		function()
      		{
      			go= true;
      			numscroll= 0;
      			scrolling= false;
      			
      			clearTimeout(timer);
      		}
  		);
  	}
	
  	jQuery("#Handle").slider( 'value' , jQuery("#Content").scrollLeft() + target );
  	
  	return false;
}

function loading( show )
{
	if ( show )
	{
		loading(false);
		jQuery("#Intro").css('background', "transparent url('/secretary/site/img/loading.gif') no-repeat 20px 10px");
		//jQuery("#Intro h1").append('<img src="/secretary/site/img/loading.gif" alt="" />');
	}
	else
	{
		jQuery("#Intro").css('background', "transparent");
		//jQuery("#Intro h1 img").remove();
	}
}

function anchorHopper()
{
	var target= location.hash.replace("#", "");
	var pageType= document.getElementsByTagName('body')[0].className;
	
	if ( target != "" )
	{	
		jQuery("#Filter a.active").removeClass("active");
		jQuery("#Filter a[rel='" + target + "']").addClass("active");
		
		if ( pageType == "type_2" )
		{
			loading(true);
			
			$.get( "/secretary/site/ajax.php",
					{
						action		: "page-hopper",
						page		: target
					},
					function (data)
					{
						loading(false);
						jQuery( "#Content ul").html("").html(data);
						calcItems();
						updateScrollbarMax();
					}
			);
		}
		else if ( pageType == "type_4" )
		{
			loading(true);
			activeCategories[activeCategories.length]= target;
			
			jQuery.get( "/secretary/site/ajax.php",
					{
						action		: "work-filter",
						categories	: target
					},
					function (data)
					{
						loading(false);
						jQuery( "#Content ul").html("").html(data);
						workHover();
						calcItems();
						updateScrollbarMax();
					}
			)
		}
		else if ( pageType == "type_5" )
		{
			loading(true);
			
			jQuery.get( "/secretary/site/ajax.php",
					{
						action		: "get-category",
						page		: target
					},
					function (data)
					{
						loading(false);
						jQuery( "#Content ul").html("").html(data);
						calcItems();
						updateScrollbarMax();
					}
			)
		}
		else if ( pageType == "type_3" )
		{
			var pos= jQuery("#Content #" + target).parent().parent().position().left;
			setTimeout( "scrollTo(" + pos + ")", 500 );
			loading(false);
		}
	}
}

function scrollTo(pos)
{
	jQuery("#Content").animate( { scrollLeft: jQuery("#Content").scrollLeft() + pos }, dist * speed );
	jQuery("#Handle").slider( "value" , jQuery("#Content").scrollLeft() );
}

/*
 * Actions
 *
 */

window.onload= function()
{	
	if ( document.getElementsByTagName('body')[0].className != "type_1" )
		setScrollBar();	
};

jQuery(function($)
{
	// IE test
	ie= ( $("#IE").css("display") == "block" );
	ie6= ( $("#IE6").css("display") == "block" );
	ie7= ( $("#IE7").css("display") == "block" );
	
	if ( ie )
	{
		$("#BackgroundImage").width( $(window).width() );
		$(window).resize(
			function()
			{
				$("#BackgroundImage").width( $(window).width() );
			}
		);
		
		if ( ie7 )
		{
			$("#Content ul li").each(
				function(i)
				{
					twidth= $(this).width();
					$("#Content ul li.top:eq(" + i + ")").width(twidth);
				}
			);
		}
	}
	
	// Set default state
	if ( document.getElementsByTagName('body')[0].className != "type_1" )
	{
		calcItems();
		workHover();
		anchorHopper();
	}
	else
	{
		$(".text").cycle({
			slideExpr: 'div.intro',
    		delay:  2800, 
   			speed:  1100,
   			before: function()
   			{
   				//$(".slides").css("height", $(this).height());
   			}
		});
		
		$("#BackgroundImage").cycle({
			slideExpr: 'img',
    		delay:  3800, 
   			speed:  500,
   			before: function()
   			{
   				$("#BackgroundImage img").css("height", "");
   			}
		}); 
	}

	// Events
	$(".bikeporterMList form").submit( function() {
		var formdata= $(this).serialize();
		var sendTo= $(this).attr("action");
		
		jQuery.post( sendTo, formdata,
			function(data, stauts) {
				$(".bikeporterMList .return").html(data);
				//$(".bikeporterMList form")[0].reset();
			}	
		);
		//alert("Sending..." + sendTo);
		
		return false;
	});

	$("#Menu li").hover(
		function()
		{
			$("#Menu li").find(":animated").stop().animate({ backgroundColor: '#EC008C' }, { duration: 300 });
			
			if ( !$(this).hasClass("active") )
			{
				$(this).children().animate({ backgroundColor: '#000' }, { duration: 500 });
			}
		},
		function()
		{
			if ( !$(this).hasClass("active") )
				$(this).children().animate({ backgroundColor: '#EC008C' }, { duration: 300 });
		}
	);
	
	$(".sections a").click(
		function()
		{
			var target= this.rel;
			var action= "";
			
			$(".sections .active").removeClass("active");
				
			if ( target != "services" )
			{
				if ( $("a[rel='" + target + "']").parent().parent().parent().parent().attr("id") == "services-list" )
				{
					action= "get-category";
				}
				else
				{
					action= "page-hopper";
					servicesActive= false;
				}
			
				$(this).addClass("active");
				
				loading(true);
			
				$.get( "/secretary/site/ajax.php",
					{
						action		: action,
						page		: target
					},
					function (data)
					{
						loading(false);
						$( "#Content ul").html("").html(data);
						calcItems();
						updateScrollbarMax();
					}
				);
			
			}
		}
	);
	
	$(".type_4 .categories a:not(.more)").click(
		function()
		{
			var category= this.rel;
			
			$(this).toggleClass("active");
			var active= $(this).hasClass("active");
			var categories= "";
			
			if (active)
			{
				activeCategories[activeCategories.length]= category;
			}
			else
			{
				activeCategories.remove(category);
			}
			
			categories= activeCategories.join(", ");
			
			if ( location.href.match( "#" ) == null )
			{
				location.href= location.href + "#" + categories;
			}
			else
			{
				var loc= location.href.substring( location.href.indexOf( "#" ) + 1 );
				location.href= location.href.replace( loc, "" ) + categories;
			}
			
			loading(true);
			
			$.get( "/secretary/site/ajax.php",
					{
						action		: "work-filter",
						categories	: categories
					},
					function (data)
					{
						loading(false);
						$( "#Content ul").html("").html(data);
						workHover();
						calcItems();
						updateScrollbarMax();
					}
			);
			
			return false;
		}
	);
	
	$(".work_full .item.image").hover(
		function()
		{
			$(this).find(".caption").fadeIn();
		},
		function()
		{
			$(this).find(".caption").fadeOut();
		}
	);
	
	// Mousewheel functionality
	// Doesn't seem to work in opera, difficulties in Safari and Firefox Mac
	if ( !window.opera )
	{
		$("#Content").mousewheel(
			function(event, direction)
			{			
				var ease= 0;
				
				dist= Math.abs(direction);
				numscroll+= dist;
		
				if ( direction < 0 )
					dir= 1; //down
				else
					dir= 0; //up
		
				if ( dir == 1 && numscroll > total_items )
					return;
				if ( dir == 0 && numscroll < 0 )
					return;

				clearTimeout(timer);
			
				if ( scrolling )
				{
					$("#Content").stop();
			
					scrollIt( numscroll, dir );
  				}
  				else
					timer= setTimeout( "scrollIt(" + numscroll + ", " + dir + ")", 100 );
			
			return false;
		});
	}
});
