if(typeof Array.prototype.indexOf != 'function'){
	Array.prototype.indexOf = function(k){
		var len = this.length;
		for(i=0;i<len;i++){
			if(this[i] == k){
				return i;
			}
		}
		return -1;
	};
}

var debug = true;

var currentAddress  = "/";
$(document).ready(function() {
	
	$("a[href^=http]:not([onclick]),a.blank").each(function() {
		if(this.href.indexOf(location.hostname) == -1 || this.className.match(/blank/)) {
			$(this).click(function(){window.open(this.href);return false;});
		}
	});
	
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
	
	//----------------- VERTICAL SLIDE NAVIGATION -----------------
	$('.acc-content').hide();
	$('.acc-content:first').show();
	$('.acc-bar:first a').hide();
	previousMenuItem = currentMenuItem = $('.acc-content:first').parent().attr('id');
	
	
	// main menu items click interaction

	$('.acc-bar a').click(function(){
		internalAddress = true;
		loadPage( $( this ).parent().parent().attr('id') );
		internalAddress = false;
		return false; //Prevent the browser jump to the link anchor
	});
	
	var internalAddress = false;
	
	//----------------- AJAX SUBCONTENT REQUESTS -----------------
	$('.menu a').click( function(){
		var address = $(this).attr('href');
		address = address.substring(1);
		internalAddress = true;
		loadPage( address );
		internalAddress = false;
		return false; 
	});
	
	var rootPages = [ "winkel", "advies", "collectie", "cadeaushop", "opruiming", "contact" ];
	
	function handleChange( event )
	{
		var path = event.path;
		if(!internalAddress) loadPage( path );

	}
	
	var pageState = [ { name:"winkel", address:"/" }, 
					{ name:"advies", address:"/" }, 
					{ name:"collectie", address:"/" }, 
					{ name:"cadeaushop", address:"/" }, 
					{ name:"opruiming", address:"/" },
					{ name:"contact", address:"/" } ];

	function loadPage( address )
	{
		trace("loadPage: "+address);
		if( address == "/" ) return;
		$(document).stopTime("sliderInterval");
		if( internalAddress ) SWFAddress.setValue(address);
		var strippedAddress = address.indexOf("/") == 0 ? address.substring(1) : address;
		var rootPageAddress = strippedAddress.indexOf("/") != -1 ? strippedAddress.substring(0,strippedAddress.indexOf("/")): strippedAddress;
		trace("rootPage: "+rootPageAddress);
		if( strippedAddress == "merken" )
		{
			loadAjaxPage( strippedAddress );
			return;
		}
		
		if( rootPages.indexOf( rootPageAddress ) != -1 && address.indexOf( currentMenuItem ) == -1 )
		{
			trace("load rootpage");
			animateRootPage( rootPageAddress );
			loadAjaxPage( strippedAddress );

		}  else {
			trace("load internal subpage");
			loadAjaxPage( strippedAddress );
		}
	}

	function animateRootPage( target )
	{
		trace( "animateRootPage "+target);
		target = target.indexOf("/") == 0 ? target.substring(1) : target;
		$('.acc-bar').slideDown();
		$('.acc-content').slideUp();
		$( "div.acc-bar a" ).show();
		if( target != "winkel" )
		{
			$( "#"+target+" > div.acc-bar" ).slideUp();
		} else {
			$( "#"+target+" > div.acc-bar a" ).hide();
		}
		$( "#"+target+" > div.acc-content" ).slideDown();
		$( "#"+currentMenuItem ).removeClass('expanded');
		$( "#"+target ).addClass('expanded');
		var previousSubContainer = $( "#"+target+" .content");
		previousSubContainer.show();
		previousMenuItem = currentMenuItem;
		currentMenuItem = target;
	}
	
	function loadAjaxPage( address )
	{
		trace("AJAX call: "+address+"\t"+currentMenuItem);
		var statObj = getPageState( currentMenuItem );
		stateObj.address = address;
		var mainContainer = $( "#"+currentMenuItem+" .acc-content");
		var subContainer = $( "#"+currentMenuItem+" .content");
		var previousSubContainer = $( "#"+previousMenuItem+" .content");
		if($.browser.msie && parseInt($.browser.version, 10) < 9){
			previousSubContainer.hide();
		}
		subContainer.fadeOut( 100, function(){
			$.get(address, function(data) {
				mainContainer.html(data);
				subContainer = $( "#"+currentMenuItem+" .content");
				$( "#"+currentMenuItem+' div.page-image-tray').css({ visibility:'visible'});
				$( "#"+currentMenuItem+' div.page-image-tray').animate({ opacity:1});
				subContainer.hide();
				subContainer.fadeIn(200);
				activateSubContent( currentMenuItem, address );
			} ); 
		} );
	}
	
	function getPageState( rootPage )
	{
		for ( var i = 0; i < pageState.length; i++ )
		{	
			stateObj = pageState[ i ];
			if( stateObj.name == rootPage ) return stateObj;
		}
		return;
	}
	
	function activateSubContent( rootPage, address )
	{
		trace( "activate subcontent:" );
		
		var contentDiv = $("#"+rootPage+" .acc-content");
		
		if( contentDiv.has('.page-image') )
		{
			setupPageSlider( { 
				container : $(".page-image", contentDiv ), 
				tray : $(".page-image-tray", contentDiv ), 
				spacer : 0, sideMargin: 75 
			} );
			$( "a.return", contentDiv ).unbind();
			$( "a.return", contentDiv ).click(function(){
				internalAddress = true;
				loadPage( $(this).attr('href') );
				internalAddress = false;
				return false;
			});
		}
		
		if( rootPage == 'collectie' )
		{
			$( 'div.product-category-top-menu a', contentDiv ).unbind();
			$( 'div.product-category-top-menu a', contentDiv ).click( function(){
				internalAddress = true;
				loadPage( $( this ).attr( 'href' ) );
				internalAddress = false;
				return false;
			} );
		}
		
		if( contentDiv.has('.product-container') ) 
		{
			$('.product-tray a').unbind();
			$('.product-tray a').click( function(){
				internalAddress = true;
				loadPage( $( this ).attr( 'href' ) );
				internalAddress = false;
				return false;
			});
			setupSlider( $(".product-container", contentDiv ), $(".product-tray", contentDiv ), 250, window );
		}
		$( '.page-detail-container', contentDiv ).height( 360 );
		$( '.page-detail-tray', contentDiv ).height( $( '.page-image li', contentDiv ).length * 360 );
		
		if( contentDiv.has('.product-detail') ) 
		{
			$( '.page-detail-tray img:not(:first)', contentDiv ).hide();
			$( '.page-image li:first', contentDiv ).addClass('current');
			$( '.page-image li a', contentDiv ).unbind();
			$( '.page-image li a', contentDiv ).click( function(){
				
				if($(this).parent().hasClass('current'))return false;
				
				var imageIndex = $(this).parent().index();
//				$( '.page-detail-tray img:visible', contentDiv ).fadeOut( 200 );
				$( '.page-detail-tray img', contentDiv ).css({zIndex: 8});
				$( '.page-detail-tray img.current', contentDiv ).css({zIndex: 9}).removeClass('current');
				
				$( '.page-detail-tray img:eq('+imageIndex+')', contentDiv ).hide().css({zIndex: 10}).fadeTo(200, 1).addClass('current');
				
				$(this).parents('ul').find('li.current').removeClass('current');
				$(this).parent().addClass('current');
				return false;
			} );
		}
		
		if( contentDiv.has('.categories-container') ) 
		{
			$( "div.product-category-container a", contentDiv ).unbind();
			$( "div.product-category-container a", contentDiv ).click( function(){
				$('a.current', $(this).parent()).removeClass('current');
				$(this).addClass('current');
				
				internalAddress = true;
				SWFAddress.setValue( $(this).attr('href') );
				internalAddress = false;
				$( ".product-subcategory-container", contentDiv ).hide();
				$( ".product-subcategory-container:eq("+$(this).index()+")", contentDiv ).fadeIn();
				return false;
			} );
			
			var strippedAddress = address.indexOf("/") == 0 ? address.substring(1) : address;
			if( strippedAddress != rootPage) {
				$( "div.product-category-container a", contentDiv ).each( function(index) {
					if( $(this).attr('href').indexOf(address) == 1 )
					{
						$(this).addClass('current');
						$( ".product-subcategory-container:eq("+index+")", contentDiv ).fadeIn();
					}
				} );
			}
			
			$( "div.product-subcategory-container a", contentDiv ).unbind();
			$( "div.product-subcategory-container a", contentDiv ).click( function(){
					internalAddress = true;
					loadPage( $(this).attr('href') );
					internalAddress = false;
				return false; 
			} );
			
		
		}
		
		//$( ".product-subcategory-container", contentDiv );
		
		
		$('.menu a', contentDiv).unbind();
		$('.menu a', contentDiv).click( function(){
			internalAddress = true;
			loadPage( parse_url( $( this ).attr('href'), 'PHP_URL_PATH' ) );
			internalAddress = false;
			return false;
		});
		
	}
	
	
	
	
	
	
});
// Ajax form handling
function ajaxForm(){
	var contact_form = $('#product-contact-form');
	var form = $('form', contact_form);
	
	$('a.close', contact_form).click(function(){
		$('body,input,textarea').unbind('keydown');
		contact_form.fadeOut(function(){
			$('p,h4', this).show();
			$('h6', this).hide();
			$('textarea', this).val('');
			$('.form-error', this).removeClass('form-error');
		});
	});
	
	var div = contact_form.parent();
	div.find('a.button.info').click(function(){
		$('#contact_extra_type').val('info');
		contact_form.fadeIn().find('h6.info').show();
		contact_form.find('span#terms-wrapper').hide().find('input').attr('disabled', 'disabled');
		$('body,input,textarea').bind('keydown', 'esc', function(){
			$('a.close', contact_form).trigger('click');
		});
	});
	div.find('a.button.order').click(function(){
		$('#contact_extra_type').val('order');
		contact_form.fadeIn().find('h6.order').show();
		contact_form.find('span#terms-wrapper').show().find('input').removeAttr('disabled');
		$('body,input,textarea').bind('keydown', 'esc', function(){
			$('a.close', contact_form).trigger('click');
		});
	});
	
	form.submit(function(){
		$('.form-error',contact_form).removeClass('form-error');
		$('#terms-wrapper').removeClass('error');
		$.post(form.attr('action'), form.serialize(), function(data){
			if(data.success){
				$('p,h4,h6', form).fadeOut('fast', function(){
					$('h6.success', contact_form ).fadeIn();
				});
			}else{
				for(var i in data.errors){
					if(i=='terms'){
						$('#terms-wrapper').addClass('error');
					}
					//var errors = data.errors[i];
					//var form_error = $('<span />', {className: 'form-error'});
					//
					//for(var j in errors){
					//	form_error.append(errors[j]);
					//}
					
					$('[name="contact['+i+']"]', contact_form).addClass('form-error');
				}
			}
			
		}, 'json');
		return false;
	});
	
}


function parse_url(str, component) {
	// http://kevin.vanzonneveld.net
	// +	  original by: Steven Levithan (http://blog.stevenlevithan.com)
	// + reimplemented by: Brett Zamir (http://brett-zamir.me)
	// %		  note: Based on http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
	// %		  note: blog post at http://blog.stevenlevithan.com/archives/parseuri
	// %		  note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
	// %		  note: Does not replace invaild characters with '_' as in PHP, nor does it return false with
	// %		  note: a seriously malformed URL.
	// %		  note: Besides function name, is the same as parseUri besides the commented out portion
	// %		  note: and the additional section following, as well as our allowing an extra slash after
	// %		  note: the scheme/protocol (to allow file:/// as in PHP)
	// *	 example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
	// *	 returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

	var	 o	 = {
		strictMode: false,
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
		q:	 {
			name:	"queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
			loose:	/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-protocol to catch file:/// (should restrict this)
		}
	};
	
	var m	= o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	i	= 14;
	while (i--) {uri[o.key[i]] = m[i] || "";}
	// Uncomment the following to use the original more detailed (non-PHP) script
	/*
		uri[o.q.name] = {};
		uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) {uri[o.q.name][$1] = $2;}
		});
		return uri;
	*/

	switch (component) {
		case 'PHP_URL_SCHEME':
			return uri.protocol;
		case 'PHP_URL_HOST':
			return uri.host;
		case 'PHP_URL_PORT':
			return uri.port;
		case 'PHP_URL_USER':
			return uri.user;
		case 'PHP_URL_PASS':
			return uri.password;
		case 'PHP_URL_PATH':
			return uri.path;
		case 'PHP_URL_QUERY':
			return uri.query;
		case 'PHP_URL_FRAGMENT':
			return uri.anchor;
		default:
			var retArr = {};
			if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
			if (uri.host !== '') {retArr.host=uri.host;}
			if (uri.port !== '') {retArr.port=uri.port;}
			if (uri.user !== '') {retArr.user=uri.user;}
			if (uri.password !== '') {retArr.pass=uri.password;}
			if (uri.path !== '') {retArr.path=uri.path;}
			if (uri.query !== '') {retArr.query=uri.query;}
			if (uri.anchor !== '') {retArr.fragment=uri.anchor;}
			return retArr;
	}
}


//----------------- TEMP -----------------
function trace( message )
{
	if( debug && !(typeof console === 'undefined') ) console.log( message );
}
