// JavaScript Document
//this function includes all necessary js files for the application
function include(file)
{

  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';
  script.defer = true;

  document.getElementsByTagName('head').item(0).appendChild(script);

}

/* include any js files here */
include('js/jquery.transform.js');
include('js/ClientSamples.js');

var currentProject = 0;

var IMG_WIDTH = 960;
var currentImg = 0;
var maxImages = 0;
var speed = 500;

var imgs;
var imgsText;

var swipeOptions=
{
	triggerOnTouchEnd : true,	
	swipeStatus : swipeStatus,
	allowPageScroll:"vertical",
	threshold:200
}

function clientClick(id)
{
	currentProject = id;
	//alert('currentProject: '+clientSampleArray[currentProject]);
	currentImg = 0;
	maxImages = clientSampleArray[currentProject].length;
	
	imgs.css("-webkit-transition-duration", 0 + "s");
	//Firefox
	if (navigator.userAgent.indexOf("Firefox")!=-1)
	{
		$('#imgs').animate({transform: 'translateX(0px)'});
	}
	//Safari, Chrome
	else
	{
		imgs.css("-webkit-transform", "translate3d(0px,0px,0px)");
	}
	
	$('#imgs').css('width', maxImages*IMG_WIDTH);
	
	var dist = IMG_WIDTH * currentImg;
	var value = (dist < 0 ? "" : "-") + Math.abs(dist).toString();
	imgs.css("-webkit-transition-duration", value + "s");
	
	$('#NextSample').fadeTo('slow', 1.0);
	$('#closeSamples').css('visibility', 'visible');
	
	
	if(currentProject < clientSampleArray.length-1)
	{
		$('#next').replaceWith('<span id="next"><a href="javascript:void" onclick="javascript:nextProject()" id="NextProject"><img src="img/rightArrow.png" /> Next Project</a></span>');
		$('#NextProject').css('visibility', 'visible');
		$('#NextProject').fadeTo('slow', 1.0, function() {
      		// Animation complete.
    	});
	}
	else
	{
		//$('#NextProject').css('visibility', 'hidden');	
		$('#NextProject').fadeTo('slow', 0.1, function() {
      		// Animation complete.
			$('#next').replaceWith('<span id="next"><img src="img/rightArrow.png" /> Next Project</span>');
			$('#next').css('visibility', 'visible');
			$('#next').css('opacity', 0.1);
    	});
	}
	
	if(currentProject > 0)
	{
		$('#previous').replaceWith('<span id="previous"><a href="javascript:void" onclick="javascript:previousProject()" id="PreviousProject"><img src="img/leftArrow.png" /> Previous Project </a></span>');
		$('#PreviousProject').css('visibility', 'visible');
		$('#PreviousProject').fadeTo('slow', 1.0, function() {
      		// Animation complete.
			
    	});
	}
	else
	{
		//$('#PreviousProject').css('visibility', 'hidden');
		$('#PreviousProject').fadeTo('slow', 0.1, function() {
      		// Animation complete.
			$('#previous').replaceWith('<span id="previous"><img src="img/leftArrow.png" /> Previous Project </span>');
			$('#previous').css('visibility', 'visible');
			$('#previous').css('opacity', 0.1);
    	});
	}
	
	//alert('currentProject: ' + currentProject);
	
	$('span#images').replaceWith('<span id="images" class="loader"></span>');
	$('ul#paginator').replaceWith('<ul id="paginator"></ul>');
	$('#copy').replaceWith('<span id="copy"></span>');
	
	$('#workSamples').fadeTo('slow', 0.1, function() {
      // Animation complete.
    });
	
	$('#ProjectContent').fadeTo('slow', 1.0, function() {
		
      // Animation complete.
	  	//$('span#images').html('<img src="../img/ZENlogoAnimation.gif" width="67" height="67" />');
		//<img src="../img/ZENlogoAnimation.gif" width="67" height="67" />
		// loop through images
		$(clientSampleArray[currentProject]).each(function(index,value){
				
				var list = $('<span id="portfolio_'+index+'"></span>');
				$('span#images').append(list);
				var curr = $("span#images span#portfolio_"+index);
				
				/*
				// set up the node / element
				_im =$("<img>");
				// hide and bind to the load event
				_im.hide();
				_im.bind("load",function(){ $(this).fadeIn(); });
				
				// append to target node / element
				$('span#images').append(_im);
				
				// set the src attribute now, after insertion to the DOM
				_im.attr('src', value);
				*/
				
				
				var img = new Image();
				$(img).load(function () {
					$(this).css('display','none');
					$(curr).removeClass('loader').append(this);
					$('span#images').removeClass('loader');
					$(this).fadeIn();
				}).error(function () {
					$(curr).remove();
				}).attr('src', value);
				
				
				//Pagination
				var plist = $('<li id="paginator_'+index+'"><a href="javascript:void" onclick="javascript:paginate('+index+')"><span id="navDotLink'+index+'" class="navDot"></span></a></li>');
				$('ul#paginator').append(plist);
				
				
				var copy = projectCopyArray[currentProject];	
				$('#copy').append(copy);
		});
		$('#navDotLink0').attr('class','navDotSelected');
    });
}

$(function()
{				
imgs = $("#imgs");
imgs.swipe( swipeOptions );
imgsText = $("#imgsText");
});

/**
* Catch each phase of the swipe.
* move : we drag the div.
* cancel : we animate back to where we were
* end : we animate to the next image
*/			
function swipeStatus(event, phase, direction, distance)
{
//If we are moving before swipe, and we are going Lor R in X mode, or U or D in Y mode then drag.
if( phase=="move" && (direction=="left" || direction=="right") )
{
	var duration=0;
	
	if (direction == "left")
		scrollImages((IMG_WIDTH * currentImg) + distance, duration);
	
	else if (direction == "right")
		scrollImages((IMG_WIDTH * currentImg) - distance, duration);
	
}
		else if ( phase == "cancel")
		{
			scrollImages(IMG_WIDTH * currentImg, speed);
		}
		
		else if ( phase =="end" )
		{
			if (direction == "right")
			{
				previousImage()
			}
			else if (direction == "left")	
			{		
				nextImage()
			}
		}
}
	
function previousProject()
{
	if(currentProject > 0)
	{
		currentProject--;
		clientClick(currentProject);
	}
}

function nextProject()
{
	if(currentProject < clientSampleArray.length-1)
	{
		currentProject++;
		clientClick(currentProject);
	}
}

function previousImage()
{
	currentImg = Math.max(currentImg-1, 0);
	scrollImages( IMG_WIDTH * currentImg, speed);
	
	selectNavDot();
}

function nextImage()
{
	currentImg = Math.min(currentImg+1, maxImages-1);
	scrollImages( IMG_WIDTH * currentImg, speed);
	
	selectNavDot();
}

function gotoImage()
{
	var dist = IMG_WIDTH * currentImg;
	var value = (dist < 0 ? "" : "-") + Math.abs(dist).toString();
	
	imgs.css("-webkit-transition-duration", 0 + "s");
	//imgsText.css("-webkit-transition-duration", 0 + "s");

	//Firefox
	if (navigator.userAgent.indexOf("Firefox")!=-1)
	{
		$('#imgs').animate({transform: 'translateX('+value+'px)'});
	}
	//Safari, Chrome
	else
	{
		imgs.css("-webkit-transform", "translate3d("+value+"px,0px,0px)");
	}
	
	selectNavDot();
}

function paginate(id)
{  
	currentImg = id;	
	selectNavDot();
	
	scrollImages( IMG_WIDTH * currentImg, speed);
}

function selectNavDot()
{
	//alert('maxImages = ' + maxImages);
	for(i = 0; i < maxImages; i++)
	{
		$('#navDotLink' + i).removeClass("navDotSelected").addClass("navDot");
	}
	$('#navDotLink' + currentImg).removeClass("navDot").addClass("navDotSelected");
	
	
	if(currentImg < 1)
	{
		$('#PreviousSample').fadeTo('slow', 0);
	}
	else
	{
		$('#PreviousSample').fadeTo('slow', 1.0);
	}
	
	if(currentImg < maxImages-1)
	{
		$('#NextSample').fadeTo('slow', 1.0);
	}
	else
	{
		$('#NextSample').fadeTo('slow', 0);
	}
}

/**
* Manuallt update the position of the imgs on drag
*/
function scrollImages(distance, duration)
{
	imgs.css("-webkit-transition-duration", (duration/1000).toFixed(1) + "s");
	//imgsText.css("-webkit-transition-duration", (duration/1000).toFixed(1) + "s");
	//inverse the number we set in the css
	var value = (distance<0 ? "" : "-") + Math.abs(distance).toString();
	
	//Firefox
	if (navigator.userAgent.indexOf("Firefox")!=-1)
	{
		$('#imgs').animate({transform: 'translateX('+value+'px)'});
	}
	//Safari, Chrome
	else
	{
		imgs.css("-webkit-transform", "translate3d("+value+"px,0px,0px)");
	}
}
// Category arrays

var Corporate = new Array('#cMango','#Egnyte','#Intellisync','#Jaxtr','#Jybe','#LeadSense','#MediaTile','#MetricStream','#Novalux','#Powerset','#ScinteraNetworks','#SiliconImage','#Twigsbury','#Unisfair','#WebJuice');
var Commerce = new Array('#DealSwarm','#Decidedotcom','#Meyer','#MortgageMatch','#Move','#NimbleCommerce','#Nor1','#Shopiks','#SideStep','#TravelMuse','#WholeTravel','#Yahoo');
var Editorial = new Array('#FoundHealth','#iFly','#Kosmix','#MeeHive','#MortgageMatch','#SideStep','#wikiHow','#Yahoo');
var Education = new Array('#Shmoop','#Twigsbury');
var Financial = new Array('#BilltoMobile', '#EntertainmentPartners', '#Intuit','#MortgageMatch','#NimbleCommerce','#WoltersKluwer');
var Health = new Array('#FoundHealth','#Intuit','#Kosmix');
var Mobile = new Array('#BilltoMobile','#DealSwarm','#Egnyte', '#EntertainmentPartners', '#Jybe','#NimbleCommerce','#Shopiks','#Twigsbury','#wikiHow');
var Search = new Array('#Kosmix','#Powerset','#SideStep','#Yahoo');
var SoftwareTechnology = new Array('#Egnyte','#EntertainmentPartners','#Encover','#ICANN','#Intellisync','#Intuit','#Jybe','#MediaTile','#Nominum','#Novalux','#Offerpal','#Openwave','#Polycom','#ScinteraNetworks','#SiliconImage','#Wealthfront','#WoltersKluwer','#Zenergo', '#GEAppliances', '#Tapjoy', '#Tapatap');
var Telecommunications = new Array('#3Jam','#AmericanWireless','#BilltoMobile','#Decidedotcom','#HearMe','#Jaxtr','#Phonezoo','#Polycom');
var Travel = new Array('#nor1','#iFly','#Kosmix','#SideStep','#TravelMuse','#Vayama','#WholeTravel','#Yahoo');

var categoryArray = [Corporate, Commerce, Editorial, Education, Financial, Health, Mobile, Search, SoftwareTechnology, Telecommunications, Travel];
//new Array("eCommerce","Editorial","Education","Financial","Health","Mobile","Search","Software","Technology","Travel");

$(document).ready(function()
{
	//FORM VALIDATION
	
	//global vars
	var form = $("#inquire");
	var contactName = $("#contactName");
	var nameInfo = $("#nameInfo");
	var email = $("#email");
	var emailInfo = $("#emailInfo");
	var message = $("#message");
	
	//On blur
	contactName.blur(validateName);
	email.blur(validateEmail);
	
	//On key press
	contactName.keyup(validateName);
	message.keyup(validateMessage);
	//On Submitting
	form.submit(function(){
		if(validateName() & validateEmail() & validateMessage())
			return true
		else
			return false;
	});
	
	//validation functions
	function validateEmail(){
		//testing regular expression
		var a = $("#email").val();
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
		//if it's valid email
		if(filter.test(a)){
			email.removeClass("error");
			emailInfo.text("");
			emailInfo.removeClass("error");
			return true;
		}
		//if it's NOT valid
		else{
			email.addClass("error");
			emailInfo.text("");
			emailInfo.addClass("error");
			return false;
		}
	}
	function validateName(){
		//if it's NOT valid
		if(contactName.val() == 'Name')
		{
			contactName.addClass("error");
			nameInfo.text("");
			nameInfo.addClass("error");
			return false;
		}
		if(contactName.val().length < 4){
			contactName.addClass("error");
			nameInfo.text("");
			nameInfo.addClass("error");
			return false;
		}
		//if it's valid
		else{
			contactName.removeClass("error");
			nameInfo.text("");
			nameInfo.removeClass("error");
			return true;
		}
	}
	function validateMessage(){
		//it's NOT valid
		if(message.val().length < 10){
			message.addClass("error");
			return false;
		}
		//it's valid
		else{			
			message.removeClass("error");
			return true;
		}
	}
	
	//END FORM VALIDATION
	
	
	// Initial fade out the floating nav bar
	$('#floatingbar').fadeOut("fast");
	$('#ProjectContent').fadeOut("fast");
	//$('#iOSSwipeContent').fadeOut("fast");
	$('#PreviousSample').fadeTo('slow', 0);
	$('#NextSample').fadeTo('slow', 1.0);
	
	//$('#closeSamples').fadeTo('fast', 0);
	//$('#PreviousProject').fadeTo('fast', 0);
	//$('#NextProject').fadeTo('fast', 0);
	
  
// Initial category list back to red
formatCategory();
	
$.preloadImages = function()
{
       for(var i = 0; i<arguments.length; i++)
       {
               $("<img />").attr("src", arguments[i]);
       }
}

$.preloadImages("../img/ZENlogoSmall.png" ,"../img/fb.png", "../img/li.png", "../img/tw.png", "../img/be.png", "../img/ZENlogoAnimation.gif", "../img/work/work_ESK_ON.png","../img/work/work_meyer_ON.png", "../img/work/work_intuit_ON.png","../img/work/work_shopiks_ON.png", "../img/work/work_move_ON.png","../img/work/work_nimblecommerce_ON.png","../img/work/work_twigsbury_ON.png","../img/work/work_travelmuse_ON.png",
"../img/work/work_wikihow_ON.png","../img/work/work_dealswarm_ON.png","../img/work/work_branding_ON.png","../img/work/work_travel_ON.png");


var $top1= $('#floatingbar').offset().top + 180;   
var $mid1 =  Math.floor($(window).height() / 2);
$('#dirbutton').data('mode','scrollup');




$('#dirbutton').click(function()
{
   $mode = $(this).data('mode');
   
   switch($mode)
   {
     case 'scrolldown':
	     $('html, body').animate({scrollTop:0}, 'slow');
		 return false;
		 break;
	 case 'scrollup':
	    $scrollpos = $('body').outerHeight();
	    $('html, body').animate({scrollTop:$scrollpos}, 'slow');
		return false;
		break;
   }
   
   
});

$(window).scroll(function()
{   

		if ($(window).scrollTop()>$top1)   
		{
		 $('#floatingbar').addClass('floater');
		 //$('#floatingbar').height(50);
		 $('#floatingbar').fadeIn("slow");
		 //$('#floatingbar').slideUp(300);
		}
		else
		{
		 //$('#floatingbar').height(0);
		$('#floatingbar').fadeOut('slow', function() {
    		$('#floatingbar').removeClass('floater');
		});
		}
});


jQuery(function(){
     $(".img-swap").hover(
          function(){this.src = this.src.replace("_OFF", "_ON");},
          function(){this.src = this.src.replace("_ON", "_OFF");
     });
});

});

//Close samples
function closeSamples()
{
		currentImg = 0;
		
		$('#closeSamples').css('visibility', 'hidden');
		$('#NextProject').css('visibility', 'hidden');
		$('#PreviousProject').css('visibility', 'hidden');
		$('#previous').css('visibility', 'hidden');
		$('#next').css('visibility', 'hidden');
		
		$('#PreviousSample').fadeTo('slow', 0);
		$('#NextSample').fadeTo('slow', 0);
		$('#ProjectContent').fadeOut("fast");
		$('#workSamples').fadeTo('slow', 1.0, function() {
		// Animation complete.
		});
}
  
// Back to red for the category a's
function formatCategory()
{
		$('#Corporate').css('color', '#C00');
		$('#eCommerce').css('color', '#C00');
		$('#Editorial').css('color', '#C00');
		$('#Education').css('color', '#C00');
		$('#Financial').css('color', '#C00');
		$('#Health').css('color', '#C00');
		$('#Mobile').css('color', '#C00');
		$('#Search').css('color', '#C00');
		$('#Software').css('color', '#C00');
		$('#Technology').css('color', '#C00');
		$('#Travel').css('color', '#C00');
}
	
function goToByScroll(id){
     	$('html,body').animate({scrollTop: $("#"+id).offset().top-50},'slow');
}

function highlight(id)
{
	var highlightColor = '#a90102';
	var fadeColor = '#ccc';
	
	for(i = 0; i < categoryArray.length; i++)
	{
		for(j = 0; j < categoryArray[i].length; j++)
		{
			$(categoryArray[i][j]).css('color', fadeColor);
			$(categoryArray[i][j]).css('font-weight', 'normal');
		}
	}
	
	for(i = 0; i < categoryArray[id].length; i++)
	{
		$(categoryArray[id][i]).css('color', highlightColor);
		$(categoryArray[id][i]).css('font-weight', 600);
	}
}

function unhighlight(id)
{
	var unhighlightColor = '#383838';
	for(i = 0; i < categoryArray.length; i++)
	{
		for(j = 0; j < categoryArray[i].length; j++)
		{
			$(categoryArray[i][j]).css('color', unhighlightColor);
			$(categoryArray[i][j]).css('font-weight', 'normal');
		}
	}
}

function clearMe(formfield)
{
	if (formfield.defaultValue == formfield.value)
	{
		formfield.value = '';
	}
}
