//global vars
var $imageArray = [['resources/images/back.png', '#back'], ['resources/images/mid.png', '#mid'], ['resources/images/front.png', '#front'], ['resources/images/depth.png', '#depth']],
	$imgCount = $imageArray.length,
	$brH,
	$frPos,
	$mdPos,
	$bkPos,
	$blPos,
	$counter = 0,
	$myXML,
	halfScreen,
	fullImage,
	halfImage,
	currentImage = 1,
	checkDir = [],
	currPages = ['home'],
	pageOpen,
	currGallery;

//////////////////////////////////////////////////////////////////////

// Simple log
function startAddress(){
	$('ul#nav li a').each(function(){
		var page = $(this).text().toLowerCase().replace(/ /g,'-');
		currPages.push(page)
	})
	
	startApp();
	
	// Event handlers
	$.address.init(function(event) {
	}).change(function(event) {
	    var name = event.value.replace(/^.(\s+)?/, "").replace(/\/$/, '').split('/');
	    pageSelect(name);
	});
}

/////////////////////////////////////////////////////////////////////////////////

//startApp()////////////////////////////////////////////////////////////////////

function startApp()
{

	$('a:not(.nonLink)').click(function(e){
		if(!$(this).hasClass('infront'))
		{
			if($(this).attr('href').replace(location.pathname, '') == '/html/work/')
			{
				getLatestWork()
			} else {
				$.address.path($(this).attr('href').replace(location.pathname, ''));
			}
		}
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
	});
	
	$('#overlay').click(function(e){
		$.address.path('/html/home/');
		e.preventDefault();
	})
	
	$('#depth, #back, #mid, #front, #blurb').css({opacity:0}).children('img').pngFix();
	
	preload(['resources/images/back.png','resources/images/mid.png','resources/images/front.png','resources/images/depth.png']);
	
	$('#projectContainer').css('marginLeft', ($(window).width()-184)+'px')
		
	var $nav = $('ul#nav li a');
	$nav.children('span.bg').css('width', '0px');
	
	$nav.hover(function(){
		$(this).stop().animate({
			paddingRight: '20px'
		}, 350, 'easeOutCirc');
		$(this).children('span.bg').stop().animate({
			width: '100%'
		  }, 350, 'easeOutCirc');
	}, function(){
		if($(this).data('active') != true)
		{			
			$(this).children('span.bg').stop().animate({
				width: 0
			  }, 500, 'easeInCirc');
		}
		$(this).stop().animate({
				paddingRight: '10px'
			}, 500, 'easeOutCirc');
	});
	
	
	$('#blurb a').hover(function(){
		$('ul#nav li:first a').animate({
			paddingRight: '20px'
		}, 350, 'easeOutCirc');
		$('ul#nav li:first a').children('span.bg').animate({
			width: '100%'
		  }, 350, 'easeOutCirc');
	}, function(){
		$('ul#nav li:first a').animate({
			paddingRight: '10px'
		}, 500, 'easeOutCirc');
		$('ul#nav li:first a').children('span.bg').animate({
			width: 0
		  }, 500, 'easeInCirc');
	});
	
	
$('#blurb a').click(function(e){
		e.preventDefault();
		$(window).scrollTo( '#contentContainer',  1700, {easing:'easeInOutQuad'} );
	});
	

	$nav.click(function(e){
		if(!$(this).attr('href') == 'http://blog.infinityweb.co.nz'){	
			e.preventDefault ? e.preventDefault() : e.returnValue = false;
		}
		
	})
	
	
	//alert('ss')
	
	$('ul#projects a').click(function(e){
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		$('#projectContainer').stop().animate({
			marginLeft: $(window).width()-553
		}, 600);
	});
	$('a.moreInfo').click(function(e){
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		$('#projectContainer').stop().animate({
			marginLeft: 0
		}, 600);
	});
	
	//
	
	$('#workNav').hover(function(){
	
	   $("#rotate").rotate({
	   	  duration:400,
	      angle:0, 
	      animateTo:180
	   });
		$('#workNav li ul').hide();
		$(this).next('.close').stop().animate({
	    	width: 100+'%'
	    }, 400, function(){
		    $('#workNav li ul').slideDown();
	    });
	}, function(){
	    $('#workNav li ul').css('left', 'auto').slideUp(function(){
	    	$('#workNav').next('.close').stop().animate({
		    	width: 38+'px'
		    }, 400);
		$("#rotate").rotate({
	   	  duration:400,
	      angle:0, 
	      animateTo:-135
	   });
	    });
	});
	
	//
	
	// Set drag scroll on first descendant of class dragger on both selected elements
	$('#viewport, #inner').dragscrollable({ acceptPropagatedEvent: true, axis : 'y'});
	
	$('.dragger').mousedown(function(){
		$(this).addClass('closed');
	})
	
	
	$(window).scroll(function () { 
      var $scr = $(window).scrollTop();
      $('#front').css('margin-top', -277  - ($scr) + "px");
     /*
 $('#mid').css('top', ($mdPos - ($scr)/3) + "px");
      $('#back').css('top', ($bkPos - ($scr/5)) + "px");
      $('#blurb').css('top', ($blPos - ($scr)/3) + "px");
*/
	 $('#mid').css('margin-top', -190  - (($scr)/3) + "px");
      $('#back').css('margin-top',  -280  - (($scr)/5) + "px");
      $('#blurb').css('margin-top',  0  - (($scr)/3) + "px");
    });
	
	
	//
	
	$(window).resize(function(){
	   resize(true);
	});
	resize(false);
	
	//scrolling
	
	$('#viewport div').mousedown(function(){
		checkDir[0] = $('#inner').scrollLeft();
		$(document).bind('mouseup', releaseMouse)
	})
	
	//image rotate setup	
	$("#rotate").rotate(45);
	
	
};

//////////////////////////////////////////////////////////////////////



function pageSelect(name)
{
	
	
	
	$('ul#nav li a').data('active', false);
	$('.'+name[1], 'ul#nav').data('active', true);
	
	$('ul#nav li a').children('span.bg').stop().animate({
				width: 0
			  }, 500, 'easeInCirc');
	$('.'+name[1], 'ul#nav').children('span.bg').stop().animate({
			width: '100%'
		  }, 350, 'easeOutCirc');
	var id = $.inArray(name[1], currPages);
	
	if($myXML == undefined)
	{
		loadXML('assets/xml/portfolio.xml', name);
	} else {
		if(id >= 0){
			switch(name[1])
			{
			case 'work':
				if(name.length > 2){
					initWork(name[2]);
				} else {
					getLatestWork();
				}
			  break;
			  case 'home':
				if(name.length > 2){
					$.address.path('/home/')
				} else {
					showHome()
				}
			  break;
			case 'services':
				if(name.length > 2){
					$.address.path('/html/'+name[1]+'/')
				} else {
					showServices();
				}				
			  break;
			case 'jobs':
				if(name.length > 2){
					$.address.path('/html/'+name[1]+'/');
				} else {
					showJobs();
				}
			  break;
			case 'contact':
				if(name.length > 2){
					$.address.path('/html/'+name[1]+'/');
				} else {
					showContact();
				}
			  break;
			}
		} else {
			//////$.address.path('/home/')
		}
		if(name == '')
		{
			$.address.path('/html/home/');
		}
		
		
	}
}

//////////////////////////////////////////////////////////////////////

function initWork(work)
{
	if(pageOpen != undefined)
	{
		slideBack('hide')
	}
	var checkArray = []
	$($myXML).find('case').each(function(i){
		var xmlName = $(this).find('name').text().toLowerCase().replace(/ /g,'-');
		checkArray.push(xmlName);
	});
	
	var id = $.inArray(work, checkArray);
	if( id >= 0 )
	{
		if( id == currGallery)
		{
		showGallery(id, false);
		} else {
		showGallery(id, true);
		}
	} else {
		$.address.path('/home/')
	}
	
	$(window).scrollTo( '#contentContainer',  1700, {easing:'easeInOutQuad'} );
}

function getLatestWork(){
	var firstProName = $($myXML).find('case:eq(0)').find('name').text().toLowerCase().replace(/ /g,'-');
	$.address.path('/html/work/'+firstProName+'/');
}

//////////////////////////////////////////////////////////////////////


function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        var img = $('<img/>')[0].src = this;
        testImg();
    });
}

//common functions
function resize(browserResize){

	

	$brH = $(window).height();
	$frPos = $('#front').position().top;
	$mdPos = $('#mid').position().top;
	$bkPos = $('#back').position().top;
	$blPos = $('#blurb').position().top;
	
	/*
	halfScreen = $(window).width() / 2;
		fullImage = $('li.image:first').width();
		halfImage = fullImage / 2;
		var counter = 0;
*/
		
		/*
if(browserResize){		
			if(this.resizeTO) clearTimeout(this.resizeTO);
		    this.resizeTO = setTimeout(function() {        
				$('#inner').stop().scrollTo( scrollPos(currentImage), {duration:600} );
		    }, 300);
	    }
*/
}

function loadXML(file, name)
{
	$.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        success: function(data) {
        	$myXML = data;
        	//alert($myXML)
        	parseXML(data); 
        	pageSelect(name);	
        },
        error: function(error)
        {
        	//alert('XML: '+error.statusText);
        }
        });
}

var defaultArray = [];

function parseXML(data)
{
	var name = '';
	var projectNameFirst = $(data).find('case:first').find('name').text();
		var projectImages = '';
	
	$('#workNav a').each(function(i){
		defaultArray.push($(this).text())
	})
	
	
	$('#workNav a').live('click', function(e){
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		if(!$(this).hasClass('infront'))
		{
			var proName = $(this).text().toLowerCase().replace(/ /g,'-');
			$('#inner').stop().scrollTo(  scrollPos($('#slider li').length) +369 , {duration:800} );
			$('#slider li').animate({opacity: 0}, 800);
			$('#workNav li ul').css('left', 'auto').slideUp(400, function(){
		    	$('#workNav').next('.close').stop().animate({
			    	width: 38+'px'
			    }, 400, function(){
			    	$.address.path('/html/work/'+proName+'/');
			    });
		    });
		}
	});
}

function changeList(priority)
{	
	var arr = [];
	$($myXML).find('case').each(function(i){
		var projectName = $(this).find('name').text();
		
		if(i == priority)
		{
			arr.reverse();
			arr.push(projectName);
			arr.reverse();
		} else {
			arr.push(projectName)
		}
	});
		
	var name = '';
	$.each(arr, function(index, value){
		if(index > 0)
		{
			var projectNameClass = value.toLowerCase().replace(/ /g,'-');
			name += '<li><a href="#" class="'+projectNameClass+' work-list"><span>'+value+'</span></a></li>'
		}
	});
	
	var origText = $('#workNav li a.infront span:not(.newSpan)').text();
	var newSpan = '<span class="newSpan">'+arr[0]+'</span>'
	$('#workNav li a.infront').append(newSpan);
	$('#workNav li a.infront span.newSpan').hide().fadeIn(function(){
		$(this).removeClass('newSpan');
	});
	$('#workNav li a.infront span:not(.newSpan)').fadeOut(function(){
		$(this).remove();
	});
	$('#workNav li ul').html(name);
	
	Cufon.replace('#workNav a', {fontFamily: 'Neutraface Slab Text Bold'});
}

function updateImagePosition()
{
	currentImage = 1;
	$('#inner').stop().scrollTo( scrollPos(currentImage), {duration:700} );
}

function loadPortfolioImages(id)
{
	var image = '<li style="height: 395px; width: 2000px;"></li>'
	$($myXML).find('case:eq('+id+')').find('image').each(function(i){
		image += '<li id="image-'+i+'" style="width: 553px; height:395px"></li>';
	})
	$('#slider').html(image);
	
	$($myXML).find('case:eq('+id+')').find('image').each(function(i){
	
		var img = $('<img />')
	    .attr('src', $(this).text() + '?' + Math.random()*99999 + new Date().getTime())
	    .load(function(){
	    	$('li#image-'+i).html($(this)).find('img').css('opacity', 0).delay(400*i).animate({
				opacity: 1
			}, 500);
	    });
	});
	
	$('#inner').stop().scrollTo( 0, {duration:0} );
	
	updateImagePosition();
}

function loadText(id)
{	
	var blurb = $($myXML).find('case:eq('+id+')').find('description').text();
	var client = 'Client: '+ $($myXML).find('case:eq('+id+')').find('client').text();
	var roles = 'Roles: ' + $($myXML).find('case:eq('+id+')').find('roles').text();
	var link = $($myXML).find('case:eq('+id+')').find('link').text();
	$('span#project-text', '.info').html(blurb);
	$('span#project-client', '.info').text(client);
	$('span#project-role', '.info').text(roles);
	if(link.length > 4)
	{
		var l = '<a href="'+link+'" class="nonLink" target="_blank">Launch website</a>';
		$('span#project-link', '.info').html(l)
	} else {
		$('span#project-link', '.info').html('');
	}
}

//functions
function showProjects()
{
	
	$('a#work', 'ul#nav').animate({
		marginRight: '170'+'px'
	}, 600);
	$('#projectList').animate({
		right: '0px'
	}, 600);
}


//check to see if all main images preloaded
function testImg(){
	$counter++
	if($counter == $imgCount)
	{
		$('#preloader').delay(1000).animate({
			opacity: 0
		}, 600, function(){
			$(this).hide();
			$('#depth').delay(0).animate({
				opacity: 1
			}, 850,function(){ $(this).css('filter','');});
			$('#back').delay(150).animate({
				opacity: 1
			}, 850,function(){ $(this).css('filter','');});
			$('#mid').delay(1200).animate({
				opacity: 1
			}, 1200,function(){ $(this).css('filter','');});
			$('#front').delay(500).animate({
				opacity: 1
			}, 850,function(){ $(this).css('filter','');});
			$('#blurb').delay(1200).animate({
				opacity: 1
			}, 1200,function(){ $(this).css('filter','');});
			
			var startVal = 1700;
			var increment = 300
			$('#nav li').each(function(i){
				$('#nav li:eq('+i+') a').delay(startVal).animate({
					marginRight: 0
				}, 600, function(){
					
					$('#blurb a').unbind('mouseenter').unbind('mouseleave').hover(function(){
						$('ul#nav li:first a').stop().animate({
							paddingRight: '20px'
						}, 350, 'easeOutCirc');
						$('ul#nav li:first a').children('span.bg').stop().animate({
							width: '100%'
						  }, 350, 'easeOutCirc');
					}, function(){
						$('ul#nav li:first a').stop().animate({
							paddingRight: '10px'
						}, 500, 'easeOutCirc');
						$('ul#nav li:first a').children('span.bg').stop().animate({
							width: 0
						  }, 500, 'easeInCirc');
					});
				});
				startVal += increment;
			});
			//
		});
	
		Cufon.replace('#blurb p', {fontFamily: 'Neutraface Slab Text Book'});
		Cufon.replace('#nav a', {fontFamily: 'Neutraface Slab Text Book'});
		Cufon.replace('#blurb p span, .title',{fontFamily: 'Neutraface Slab Text Bold'});
		Cufon.replace('#blurb a', {fontFamily: 'Neutraface Slab Text Bold'});
	}
};

//////////////////////////////////////////////////////////////////////

//slide functions

function scrollPos(idNum){
	num = ((2000+ (553*(idNum-1))+(3*(idNum-1)))) - (369);
	return num;
}
	

function releaseMouse()
{
	checkDir[1] = $('#inner').scrollLeft();
	checkDrag(checkDir[0], checkDir[1]);
	$('.dragger').removeClass('closed');
	$(document).unbind('mouseup')
}

function checkDrag(begin, end)
{
	var dir = '';
	var travelled = Math.abs(begin - end)
	if(begin > end)
	{
		dir = 'left';
	} else if(begin < end) {
		dir = 'right';
	} else {
		dir = undefined;
	}
	
	if(travelled > 60)
	{
		if(dir == 'right')
		{
			currentImage++
			if(currentImage >= $('#slider li').length){
				currentImage = $('#slider li').length - 1
			}
			$('#inner').stop().scrollTo( scrollPos(currentImage), {duration:600} );
		} else if(dir == 'left')
		{
			currentImage--
			if(currentImage <= 0)
			{
				currentImage = 1
			}
			$('#inner').stop().scrollTo( scrollPos(currentImage), {duration:600} );
		}
	} else {
		$('#inner').stop().scrollTo( scrollPos(currentImage), {duration:300} );
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$.fn.pngFix = function() {
  if (!$.browser.msie || $.browser.version >= 9) { return $(this); }

  return $(this).each(function() {
    var img = $(this),
        src = img.attr('src');

    img.attr('src', 'resources/images/x.gif')
        .css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + src + "')");
  });
};

if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

//pages//////////////////////////////////////////////////////////////////////////////////////////////////////////////

function showHome()
{
	if(pageOpen != undefined)
	{
		slideBack('hide')
	}
	showGallery(0);
}

function showOverlay()
{
	$('#pageContainer').show();
	$('#overlay').fadeIn();
}

function hideOverlay()
{
	$('#pageContainer').hide();
	$('#overlay').fadeOut();
}

function slideBack(exit)
{
	if(pageOpen != undefined)
		{
		pageOpen.animate({
				marginRight: - pageOpen.width() + 'px'
		}, 700, function(){
			if(exit == 'hide')
			{
				hideOverlay();
				pageOpen = undefined;
			}
		});
	}
}

//gallery
function showGallery(id, swap)
{
	if(swap)
	{
		
		changeList(id);
		loadPortfolioImages(id);
		loadText(id);
	} else {
	if(currGallery >=0)
		{
		} else {
			changeList(id);
			loadPortfolioImages(id);
			loadText(id);
		}
	}
		currGallery = id;
}

//services
function showServices(){
	
	slideBack()
	showOverlay();
	showGallery(0);
	//alert('a');
	
	pageOpen = $('#servicesContainer');
	$('#servicesContainer').delay(700).animate({
			marginRight: '0px'
	}, 700);
	
	
	//funcs
	$('.leftTabs a').click(function(e){
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		hideContainer( $(this).attr('class').split(' ')[0]);
		
	});
	
	var currentContainer = '';
	
	$('#T-1, #T-2, #T-3').hide();
	$('.T-1, .T-2, .T-3').parent().removeClass('tabs-selected');
	showContainer('T-1');
	
	function showContainer(id)
	{
		currentContainer = id;
		$('#'+id).fadeIn(400)
		$('.'+id).parent().addClass('tabs-selected')
	}
	
	function hideContainer(id)
	{
		$('#'+ currentContainer).fadeOut(400);
		$('.'+currentContainer).parent().removeClass('tabs-selected');
		showContainer(id);
	}
	
	$('.tabs-container a.nextStepBtn').click(function(e){
		e.preventDefault ? e.preventDefault() : e.returnValue = false;
		var link = $(this).attr('class').split(' ')[0];
		hideContainer(link);
		
	})
}

//jobs
function showJobs()
{
	slideBack();
	showOverlay();
	showGallery(0);
	pageOpen = $('#jobsContainer');
	pageOpen.delay(700).animate({
			marginRight: '0px'
	}, 700);
}

//contact
function showContact()
{
	slideBack();
	showOverlay();
	showGallery(0);
	pageOpen = $('#contactContainer')
	pageOpen.delay(700).animate({
			marginRight: '0px'
	}, 700);
}

