var aboutOpen = false;
var btnFunc = 'click';
var aniSpeed = 1200;
var animating = false;
var gallery;

var imgPath = 'large';
var portfolioArr = new Array(new image('fernando-2560-x1600.jpg', false), new image('innocent-2560-x-1600.jpg', false), new image('overall-woman-2560x1600.jpg', false), new image('rocket-man-2560-x-1600.jpg', false), new image('scirocco-2560-x-1600.jpg', false), new image('the-green-2560-x-1600.jpg', false), new image('train-2560-x-1600.jpg', false));

var totalImages = portfolioArr.length;
var imageArray = new Array();

var timerCount = 0;
var marginAmount = 1000;
var intervalID;
var keyword;

function image(url, loaded) {
 this.url = url;
 this.loaded = loaded;
}


function init(_keyword, justForm) {
	keyword = _keyword;
	if(keyword == '') keyword = 'N/A';
	
	if(justForm == true) return;
	
	$('#aboutPage').css({
		'left' : '-' + $(this).width() + 'px',
		'width' : '100px'
	});
	$('#aboutTab').bind(btnFunc, function() {
		if(!animating) {
			if(!aboutOpen) openAbout();
			else closeAbout();
			aboutOpen = !aboutOpen;
		}
	});
	
	$('#contactTab').bind(btnFunc, function() {
		$('#contactForm').animate({'top' : '0px'}, 800, 'easeInOutQuint');
	});
	$('#closeForm').bind(btnFunc, function() {
		$('#contactForm').animate({'top' : '-380px'}, 800, 'easeInOutQuint');
	});
	
	if(isiPhone() || isiPad()) {
		updateOrientation(false);
	} else {
		setScreenSize();
	}
	
	
	$.supersized({	vertical_center : 0,		//Portrait images will not exceed browser height
					slides	:  [ { image : "" } ]});
	startLoading();
	
	
	$(window).load(function(){
		$('#aboutTab').css({'display' : 'block'});
		$('#contactTab').css({'display' : 'block'});
	});
}

function startLoading(reload) {
	
	if(reload != true) {
	$('#supersized').append('<img src="images/bkg/' + imgPath + '/' + portfolioArr[0].url + '" />');
	
	$('#supersized img').load(function() {
		var currHeight = $(document).width() + 'px';
		imageArray.push($(this));
		$('#supersized').call_resize();	
		$(this).addClass('active_slide').fadeIn(aniSpeed, loadAllImages);
		
	});
	} else {
		loadAllImages(true)
	}
	
}

function loadAllImages(reload) {
	
  		//load remaining images
		var i=1;
		if(reload) i=0;
		while(i<=totalImages-1) {
			$('#supersized').append('<img src="images/bkg/' + imgPath + '/' + portfolioArr[i].url + '" />');
			var img = $('#supersized img:last-child');
			imageArray.push(img);
			img.onLoad = imageLoaded(i);
			img.detach();
			i++;
		}
		
		if(reload) {
			$(imageArray).each(function() { 
				$(this).removeClass('active_slide').detach();
			});
			$(imageArray[timerCount]).appendTo($('#supersized')).addClass('active_slide');
			$('#supersized').call_resize();	
		} 
		
		startTimer();
}

function imageLoaded(i) {
	imageArray[i].loaded = true;
}

function startTimer() {
	intervalID = setInterval("checkIfLoaded()", 6000);
}


function checkIfLoaded() {
	if(imageArray[timerCount].loaded) {
		moveSlide();
	} else {
		imageArray[timerCount].onLoad = moveSlide();
	}
}

function moveSlide() {
	var currHeight = $('#supersized .active_slide').width();
	var curr_slide = imageArray[timerCount];
	
	timerCount ++;
	if(timerCount > totalImages-1) timerCount = 0;	
	
	var new_slide;
	if(timerCount == totalImages) new_slide = imageArray[0];
	else new_slide = imageArray[timerCount];
	$(new_slide).appendTo($('#supersized')).addClass('new_slide');

	$('#supersized').call_resize();
	$(new_slide).animate({left : currHeight}, 0);
	
	$(curr_slide).animate({left : - currHeight}, aniSpeed, "easeInOutQuint", function() {
		$(curr_slide).css('left',currHeight).removeClass('active_slide').detach();
	
	});
	
	$(new_slide).animate({left : 0}, aniSpeed, "easeInOutQuint", function() {
		$(new_slide).removeClass('new_slide').addClass('active_slide');	
	});
	
}


function openAbout() {
	animating = true;
	$('#aboutPage').css({'display' : 'block', 'left' : - $(this).width() + 'px','width':'100%'}).animate({"left":"0px"}, 1300, "easeInOutQuint", function() {
		clearInterval(intervalID);
		gallery = $('#supersized').detach();
		animating = false;
	});
	
	$('#main').css({'padding-bottom' : (195) - $('#copy').height() + $('#aboutCopy').height() + 'px'});

	$('#dark').delay(500).fadeIn(0);
	$('#light').delay(500).fadeOut(0);
	
	$('#strapline h3').css({"color":"#000000"});
	$('#footer').css({"color":"#000000"});
	$('#aboutImg').css({'display':'none'});
	$('#homeImg').css({'display':'block'});
}
	

function closeAbout() {
	animating = true;
	$(gallery).appendTo('body');
	startTimer();
	$('#aboutPage').animate({"left":"-" + $(this).width() + "px"}, aniSpeed, "easeInOutQuint", function() {
		$(this).css({'display' : 'none'});
		$('#main').css({'padding-bottom' : '180px'});
		if(isiPhone() && window.orientation == 0) $('#footerwrap').css({'display' : 'block'});
		animating = false;
	});
	$('#light').delay(500).fadeIn(0);
	$('#dark').delay(500).fadeOut(0);
				
	$('#strapline h3').css({"color":"#FFFFFF"});
	$('#footer').css({"color":"#ffffff"});
	$('#aboutImg').css({'display':'block'});
	$('#homeImg').css({'display':'none'});
	
}


function isiPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}
function isiPad(){
	 return (
        (navigator.platform.indexOf("iPad") != -1)
    );
}

function setScreenSize() {
	imgPath = 'desktop';
	var screenwidth = screen.width;
	if(screenwidth < 1400) {
		imgPath = 'desktop';
	}
}

function updateOrientation(reload){
    switch(window.orientation){
        case 0:
			imgPath = 'v';
			if(!isiPad()) {
				if(!aboutOpen) $('#footerwrap').css({'display' : 'block'});
			}
		break;
		case -90:
			imgPath = 'h';
			if(isiPhone() && aboutOpen) $('#footerwrap').css({'display' : 'none'});
		break;
		case 90:
			imgPath = 'h';
			if(isiPhone() && aboutOpen) $('#footerwrap').css({'display' : 'none'});
		break;
		case 180:
			if(!isiPad()) {
				if(!aboutOpen) $('#footerwrap').css({'display' : 'block'});
			}
			imgPath = 'v';
		break;
    }
   
    if(isiPad()) imgPath = 'ipad/' + imgPath;
    if(isiPhone()) imgPath = 'ipad/' + imgPath;
    
     if(reload) {
    	clearInterval(intervalID);
    	imageArray = [];   	
    	$('#supersized img').each(function() {
    		$(this).remove();
    	});
    
    	startLoading(true);
    }
}

function checkFields() {
		var ok = true;
		var errStr = "Please fill the following fields correctly: \n";
		if($('#enquiryForm #name').val() == '') {
			ok = false; 
			errStr += 'Name \n';
		}
		if(isValidEmail($('#enquiryForm #email').val()) == false) {
			ok = false; 
			errStr += 'Email Address \n';
		}
		if($('#enquiryForm #organisation').val() == '') {
			ok = false;
			errStr += 'Organisation Name \n';
		}
		
		if($('#enquiryForm #phone').val() == '') {
			ok = false;
			errStr += 'Phone Number \n';
		}
		
		if($('#enquiryForm #information').val() == '') {
			ok = false;
			errStr += 'Information \n';
		}
		
		if(!ok) {
			return errStr;
		} else {
			return true;
		}
	}
	
function isValidEmail(email) {
 	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
 	var address = email;
	if(reg.test(address) == false) {
   		return false;
	} else {
   			return true;
   		}
}

function sendQuote(miniForm) {
	var errors = checkFields();
	if(errors == true) {
	$('#preloader').css({display : 'block'});
	var _name = $('#enquiryForm #name').val();
	var _email = $('#enquiryForm #email').val();
	var _organisation = $('#enquiryForm #organisation').val();
	var _phone = $('#enquiryForm #phone').val();
	var _information = $('#enquiryForm #information').val();
	
	var datastring = '&name=' + _name + '&email=' + _email + '&organisation=' + _organisation + '&phone=' + _phone + '&information=' + _information;
	jQuery.ajax({
		type: "GET",
		data: datastring,
		url: "quote-ajax.php",
		success: function(results) {
			//reset form
			if(results != 'error') {
				//send tracking to Epic
				sendTracking(_name);
				
	 			//all sent, reset form
	 			$(':input').each(function() { 
					$(this).val(""); 
				});
				$('#preloader').css({display : 'none'});
				if(miniForm != 'true') $('#contactForm').animate({'top' : '-380px'}, 800, 'easeInOutQuint');
				else alert('Many thanks for your enquiry. A member of the Milky Tea team will be in touch with you shortly.');
			} else {
				alert('there has been an error sending this quote, please try again');
			}
		}
	})
	} else {
		//error
		alert(errors);
	}
}

function sendTracking(name) {
	$(document.body).append('<iframe style="display:none" src="http://www.epicnewmedia.co.uk/tracking/milkytea/index.php?google=' + keyword + '&name=' + name + '"></iframe>');
}
