$(function()
{
	// INIT
	
	var prevState, currState, prevSlide, currSlide, prevColor, currColor;
	
	if ( $(this).url().segment(1) == 'collection' )
	{
		initProductView();
		$('.fb_button').live('click', function() { facebookshare() });	
		$('#colorbox_close').live('click', function() { $.address.value( '' ) });
		// $('button#zoom').live('click', function()
		// {
		// 	
		// })	
	}
	
	
	 
	
	
	
	// 
	// $('.prod_img').live( function()
	// {
	// 	$(this).hide();
	// });
	
	// deep linking
	
	$.address.change(function()
	{		
		switch ($('body').attr('class'))
		{
			case 'retailers':
				loadRetailers();
				break;
				
			case 'slides':
				loadSlides();
				break;
			
			case 'collection':
				loadCollection();				
				break;
			
			default :
				// trace('andre sider');
				break;
		};
		if ($(document).url().attr('hash'))
		{
			_gaq.push(['_trackPageview', $(document).url().toString()]);
		}
	});
	
	$('#prod_box .swatch').live('click', function()
	{
		$.address.path($.address.pathNames()[0] + '/color-' + $(this).attr('id').split('-')[1]);
		return false;
	}).css({'cursor':'pointer'});
	
	$('#prod_box #img_viewer a').live('click', function()
	{
		if ( $.address.pathNames()[2] == 'zoom' )
		{
			$.address.path( $.address.pathNames()[0] + '/' + $.address.pathNames()[1] );
		}
		else
		{
			$.address.path( $.address.value() + '/zoom' );
		};
		return false;
	});
	
	$('#zoomed_image').live('click', function()
	{
		$.address.path( $.address.pathNames()[0] + '/' + $.address.pathNames()[1] );
	}).css({ 'cursor' : 'pointer' });
	
	// FUNCTIONS
	

	function trackAjax()
	{
		if ($(document).url().attr('hash'))
		{
			_gaq.push(['_trackPageview', $(document).url().toString()]);
		}		
	}

	
	function loadCollection()
	{
		prevState = currState || 'nothing';	
		prevColor = currColor || 'nada';	
		currState = $.address.pathNames()[0] || 'nothing';
		currColor = $.address.pathNames()[1] || 'nada';
		// trace(prevState, currState, prevColor, currColor);
		if ( !$(this).url().segment(5) )
		{
			toggleColorbox();
		}
		else
		{
			document.location.href = 'http://' + $(this).url().attr('host') + '/' + $(this).url().segment(0) + '/' + $(this).url().segment(1)+ '/' + $(this).url().segment(2)+ '/' + $(this).url().segment(3)+ '/' + $(this).url().segment(4)+ '/#/' + $(this).url().segment(5) + '/' + $(this).url().segment(6) ;
			// document.location.href = 'http://dale.no.s10.subsys.net';
		}
		
	};
	
	function loadSlides()
	{
		if ( $.address.pathNames()[0] ) // url has hash
		{
			$.ajax(
			{
				type:"get",
				dataType: 'html',
				url: '/' + countrycode + '/slide_ajax/' + $.address.pathNames()[0],
				beforeSend: function()
				{
					$('#curtain').fadeIn();
					prevSlide = $('#col1').attr('class');
				},
				success: function(data) 
				{
					$('#col1').fadeOut(1000, function() { $(this).remove() });
					$('#curtain').after(data);
					$('#col1').hide();
					$('#col1').delay().fadeIn(1000);
					$('#curtain').delay(1000).fadeOut();	
					trackAjax();				
				}
			});			
		}
	};
	
	
	function loadRegions()
	{
		// trace($.address.pathNames()[0] + '/' + $.address.pathNames()[1]);
		$('#regions').slideUp(function()
		{
			$('#regions h2').show();
			$('#regions #regionlist').show();
			
			$('#regionlist').load('/' + countrycode + '/retailers_ajax/' + $.address.pathNames()[0], function(data, status, response) 
			{
				$('#regions').slideDown();
			});
		});
		
	}
	
	function loadCities()
	{
		$('#cities').slideUp(function()
		{
			$('#cities h2').show();
			$('#cities #citylist').show();
			
			
			$('#citylist').load('/' + countrycode + '/retailers_ajax/' + $.address.pathNames()[0] + '/' + $.address.pathNames()[1], function(data, status, response) 
			{
				$('#cities').slideDown();
			});
		});
	}
	
	function loadRetailerTable()
	{
		$('#col2').slideUp(function()
		{
			$('div#col2').load('/' + countrycode + '/retailers_ajax_tab' + $.address.value(), function(data, status, response) 
			{
				$('#col2').slideDown();
			});
		});
	}
	
	
	function loadRetailers()
	{
		switch($.address.pathNames().length)
		{
			case 3:				
				if ($('#regionlist').is(":hidden")) loadRegions();
				if ($('#citylist').is(":hidden")) loadCities();			
				loadRetailerTable();						
				break;
			
			case 2:
				if ($('#regionlist').is(":hidden")) loadRegions();				
				loadCities();			
				loadRetailerTable();			
				break;
			
			case 1:
				loadRegions();			
				$('#col2').slideUp();
				$('#cities').slideUp();			
				break;
			
			case 0:
				$('#col2').slideUp();
				$('#cities').slideUp();
				$('#regions').slideUp();
				break;
		};
		trackAjax();
	};
	
	function toggleColorbox() // dersom nytt produkt, endre innhold i boks, hvis ikke, endre kun bilde
	{
		if ( $.address.value() != '/' )
		{
			if ( prevState != currState )
			{
				$.fn.colorbox({opacity: '0.5', width: '740px', height: '640px', href:window.location.pathname +  $.address.pathNames()[0] + '/color-1', onComplete:function() 
				{ 
					$('.prod_img').hide(); 
					initProductView(); 
					if ( $.address.pathNames()[2] == 'zoom' )
					{
						zoomImage();
					}
				}, onClosed:function() 
				{ 
					$.address.value('') 
				}});
			}
			else if ( prevColor != currColor )
			{
				toggleProductVisible();
			}
			
			if ($.address.pathNames()[2] == 'zoom' )
			{
				zoomImage();
				$('button#zoom').css({ 'background-image' : '/images/gui/zoom-out.png' });
			}
			else if ( $.address.pathNames()[2] != 'zoom' )
			{
				$('#zoomed_image').fadeOut();
				$('button#zoom').css({ 'background-image' : '/images/gui/zoom-in.png' });				
			}
			
			trackAjax();
		}
		else
		{
			$.fn.colorbox.close();
		}
	};
	
	function zoomImage()
	{
		$.ajax(
		{
			type:"get",
			dataType: 'html',
			// url: $(this).url().host(),
			url: $(this).url().toString().split('/#/')[0].replace('collection', 'ajax_zoom') + $(this).url().toString().split('#')[1],
			beforeSend: function()
			{
				$('#curtain').fadeIn();
			},
			success: function(data) 
			{
				$('#zoomed_image').remove();
				$('#curtain').after(data);
				$('#zoomed_image').hide();
				$('#zoomed_image').css({ 'position' : 'absolute', 'top' : '0', 'left': '-540px' }).draggable({ containment : [-500,-1000,500,200] }).fadeIn( 1000, function() { $('#curtain').fadeOut(); } );
				trackAjax();
				// $('.prod_img').fadeOut();
				// trace( $(this).url().toString().split('/#/')[0].replace('collection', 'ajax_zoom') + $(this).url().toString().split('#')[1] );
			}
		});
		// 			$('#curtain').fadeIn();
		// trace( $('#prod_box #img_viewer .prod_img').is(':visible').find('a').attr('href') );

		
	}
	
	
	function initProductView() // flytter swatches til riktig sted
	{
		$('#prod_box .swatch').appendTo('#swatches');
		$('#prod_box h2').after($('#prod_box #swatches'));
		$('#prod_box ul').after($('#prod_box #logos'));
		toggleProductVisible();		
	};
	
	function toggleProductVisible() // viser og skjuler genser basert på siste ledd i urlen
	{
		if ($.address.pathNames()[1] != undefined) //$.address.pathNames()[1]
		{	
			$('.prod_img').fadeOut();
			$('#color-' + $.address.pathNames()[1].split('-')[1]).fadeIn();	
			trackAjax();			
		}
	};
	
	function facebookshare()
	{
		// trace( 'sharing on facebook: ' + 'http://dale.no.s10.subsys.net' + window.location.pathname +  $.address.pathNames()[0] + '/' + $.address.pathNames()[1] );
		var 
		d=document,
		f='http://www.facebook.com/share',
		l=d.location,
		e=encodeURIComponent,
		ze_url_ja = 'http://dale.no.s10.subsys.net' + window.location.pathname +  $.address.pathNames()[0] + '/' + $.address.pathNames()[1],
		und_ze_title_ja = 'Dale of Norway',
		p='.php?src=bm&v=4&i=1252924906&u='+e(ze_url_ja)+'&t='+e(und_ze_title_ja);
		1;
		try 
		{
			if (!/^(.*\.)?facebook\.[^.]*$/.test(l.host))throw(0);
			share_internal_bookmarklet(p)
		}
		catch(z) 
		{
			a=function() 
			{
				if (!window.open(f+'r'+p,'sharer','toolbar=0,status=0,resizable=1,width=626,height=436'))
				l.href=f+p
			};
				if (/Firefox/.test(navigator.userAgent))
				setTimeout(a,0);
				else
				{
					a()
				}
			}
		void(0);
		
		_gaq.push(['_trackPageview', 'Facebook share: ' + $(document).url().toString()]);

			
	}
	
	
// 	
// 	$('#colorbox #img_viewer a').live('click', function()
// 	{
// 		trace('img_viewer klikk');
// 		$.address.value( 'test' );
// 		// $.address.path( $(this).url().segment(5) + '/' + $(this).url().segment(6) + '/zoom' );
// 		// if ( $(this).url().segment(7) == 'zoom' )
// 		// {
// 		// 	// trace('zoom');
// 		// 	$.address.path( $(this).url().segment(5) + '/' + $(this).url().segment(6) );
// 		// }
// 		// else
// 		// {
// 		// 	// trace('zoom out');
// 		// 	
// 		// }
// //		$.address.path( $(this).url().segment(5) + '/' + $(this).url().segment(6) + '/zoom' );
// 		return false;
// 	});
	
});

