//var currentPage = 0;
var firstPageBannersCount = 3;
var headSlidingPanelAnimationTime = 3500;
var headPanelDelayTime = 10;
var bannerSwitchTimeOut = 4000;
var bannerSwitchFadeOutTime = 2000;
var bannersSwitchingTime3rdPage = 4000;
var bannersSwitchingTime3rdPageDelay = 500;
var pageOverFadeOutTime = 2000;
var changePageAnimationTime = 2000;
var showItemsPanelAnimationTime = 600;
var webpagesSliderItemFadingAnimationTime = 600;
var pageHeight = 1052;
var toolTipFadeTime = 400;
var toolTipFadeDelay = 400;
var panelFadeDelay = 0;
var goToPageInProgress = false;
var pagesLoaded = {};
var currentItem = {};
var howWeDoItBannerId = 0;
var headerAnimationTypeUp = 'easeInOutBack';
var headerAnimationTypeDown = 'easeInOutBack';
var serverName = window.location.host//'http://tmesolutions4.dev/';
var dontStartSelfShowingImages = false;
var pageNamesArray = [ ' ','Home','why-go-smart','our-uniqueness','features','benefits','contact-us'];
var currentPage = 0;
var pageCount = 6;
var stopPortfolioAnimation = false;
var pageStartUp = true;
//var hashHistory = [];
var dontUpdateHash = false;

function setCookie( name, value ) {
	document.cookie = name + '=' + value + ';path=/;';
}

function unsetCookie( name ) {
	document.cookie = name + '=; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/;';
}
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) {
		return null;
	}
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) {
		end = document.cookie.length;
	}
	return unescape( document.cookie.substring( len, end ) );
}
function activateHeadMenuItem(id){
	$( '.head .menu .item' ).removeClass('active');
	$( '#head_menu_item_' + id ).addClass('active');
}
function checkText(text){
	if( typeof(text) == 'undefined' || text == ''){
		return false;
	}
	return true;
}
function validateEmail(text){
	var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( !filter.test( text )){
		return false;
	}	
	return true;
}
function submitThisForm(button){
	$(button).parents('form').submit();
}
function sendForm(form){
	$.post('email.html',$(form).serialize(),function(data){
		if( data == '1' ){
			var name = $( 'input.firs_name',form ).val();
			luvBasket.clearItems();
			$('input', form).each(function(){
				if( $(this).val() != '' )
					$(this).val('').blur();
					$( '.defaultText', form ).addClass( 'blured' ).text('');
			});
			if( $('textarea', form).val() != '' )
				$('textarea', form).val('').blur();
			showCustomPopup('Thanks ' + name + ' for your enquiry, we’ll contact you shortly.<br/>Or you can call us on 0800 634 8600.', 'Thanks!');
			trackEvent( 'general', 'Contact form submitted' );
		}else{
			showCustomPopup('Something went wrong please try again later');
		}
	});	
}
function validateForm( form ){
	if ( $(form).attr('id') == "foot_form" ) {
		$( '#foot' ).die('focusout');
	}
	var errorMsg = "We need the fields in red so we can get back to you!<br/>";
	var errors = false;
	if (! ( checkText( $( '.email',form ).val() ) || checkText( $( '.phone',form ).val() ) ) ){
		errors = true;
		errorMsg += " - Email or contact number <br/>";
		$('.email',form).parent().addClass('marked');
		$('.phone',form).parent().addClass('marked');		
	}
	if ( ! ( ( ! checkText( $( '.email',form ).val() ) ) || validateEmail( $( '.email',form ).val() ) ) ){
		errorMsg += " - Email - we need it in email format<br/>";
		errors = true;
		$('.email',form).parent().addClass('marked');
	}
	if ( ! checkText( $( '.firs_name',form ).val() ) ){
		errorMsg += " - First name<br/>";
		errors = true;
		$('.firs_name',form).parent().addClass('marked');
	}
	/*
	if ( ! checkText( $( '.last_name',form ).val() ) ){
		errorMsg += " - Last name is mandatory";
		errors = true;
		$('.last_name',form).parent().addClass('marked');
	}
	*/		
	if( ! errors ){
		if( $( form ).parents('#vacancies_detail_popup').length == 1 ){
			sendVacanciesForm(form);
		}else{
			sendForm(form);
		}
	} else {
		showCustomPopup( errorMsg , "Missing some details!");
	}
	return false;
}
function goToPagePB( id ){
	howWeDoItBannerId = id;
	goToPage( 2 );
}
function updateCurrentPage(){
	
	var temp = parseInt( $(document).scrollTop() / pageHeight );
//	console.debug('updatecurrentpage = '+temp + 'scrolltop = '+ $(document).scrollTop());
	if( ( ($(window).scrollTop() % pageHeight) + $(window).height() > pageHeight + 90 ) && ( temp + 1 ) != headIsInPage ){
//		$( window ).scrollTop( $( window ).scrollTop()+1 );
		currentPage = temp + 1;
	} else if( ( ( $(window).scrollTop() % pageHeight )  <= 180 ) && temp != headIsInPage ){
		currentPage = temp;
//		$( window ).scrollTop( $( window ).scrollTop()-1 );
	} else if ( pageStartUp ) {
		currentPage = temp;
		pageStartUp = false;
	}
	updateHash ( 'page',currentPage );
	return currentPage;	
}
function searchArray( value, arr ){
	var result = null;
	$.each( arr, function(index,item){
		if ( item === value ){
			result = index;			
		}
	});
	return result;
}
var internalHashChange = false;
function updateHash( item, value ){
	if( !goToPageInProgress ){
		if ( getHash(item) != value ){
			var seperator = '--';
			var hash = window.location.hash;
			hash = hash.substring(1, hash.lenght);
			var params = hash.split('--');
			if ( item == 'page' ){
				params[0] = encodeURIComponent( pageNamesArray[ value ] );
				if( value != 1 ){
					params[1] = ''
				} else if ( currentPortfolioItem != 0 ){
					params[1] = encodeURIComponent( portfolio_names[ currentPortfolioItem ] );
				}
			} else if ( item == 'portfolio' ){
				if ( value ){
					params[1] = encodeURIComponent( portfolio_names[ value ] );
				} else {
					params[1] = '';
				}
			}
			hash = '';
			$.each( params, function( key, value ){
				if ( value !== '' ){
					hash += value + seperator;
				}
			});
			internalHashChange = true;
			setTimeout(function(){internalHashChange=false},50);
			var result = hash.substring(0,hash.length-seperator.length);
//			hashHistory.push( result ); 
			window.location.hash = result;
		}		
	}
}
function getHash( item ){
	if ( window.location.hash ){
		var hash = window.location.hash;	
	} else if ( window.location.search ){
		var hash = decodeURIComponent( window.location.search );
	} else {
		return null;
	}
	var seperator = '--';
	hash = hash.substring( 1, hash.lenght );
	var params = hash.split( seperator );
	if ( item == 'page' ){
		return searchArray( decodeURIComponent( params[0] ), pageNamesArray );
	} else if ( item == 'portfolio' ) {
		if ( typeof( params[1] ) != "undefined" ){
			return searchArray( decodeURIComponent( params[1] ), portfolio_names ) ;
		} else { 
			return null;
		}			
	}
}
function toggleBlur(el){
	if( $(el).val() == '' ){
		$(el).toggleClass('blured');
	}
	$(el).parent().removeClass('marked');
}
function showCustomDropdown ( el ){
	if($( el ).siblings( '.dropdownExpand' ).is(':hidden')) {
		$( el ).siblings( '.dropdownExpand' ).show(0);//.focusout(function(){$( this ).hide(0);});		
	}
}
function selectOption ( el ){
	var value = $( el ).text();
	$( el ).parents( '.customDropdown' ).find( '.budget_input' ).val( value );
	$( el ).parents( '.customDropdown' ).find( '.defaultText' ).text( value ).removeClass('blured');
	$( el ).parents( '.dropdownExpand' ).hide(0);
}
function toggleCheckbox(el){
	if( $( el ).is('.on') ){
		$( el ).removeClass('on');
		$( 'input', el ).attr('checked', false);
	}else{
		$( el ).addClass('on');
		$( 'input', el ).attr('checked', true);
	}
}
function goToPortfolioItemFromAnywhere( id ){
	$( '#foot' ).focusout();
	goToPage( 1, function(){
		goToPortfolioItem( id );
	} );
}
function goToPage( number , callback ){
	goToPageInProgress = true;
	updateCurrentPage();
	if( number == 1 && currentPage == 1 && currentPortfolioItem !== 0){
		backToPortfolio();
	} else {
//		console.log('goToPage = '+ number);
//		dontUpdateHash = true;
		$('html:not(:animated),body:not(:animated)').animate({scrollTop: pageHeight * parseInt( number ) }, changePageAnimationTime, function(){
			goToPageInProgress = false;
			updateCurrentPage();
			if ( typeof( pagesLoaded[number] ) == 'undefined' ){
				showPage( number, function(){ if ( typeof( callback ) == 'function' ){ callback(); } } );
			} else if ( number == 2 ){
				stopSelfSkippingBanners()
				PBGoTo( howWeDoItBannerId );
			} else if ( typeof callback == 'function' ){
				callback(); 
			}
		});
	}
	trackEvent(pageNamesArray[number],'View');
}
function nextPage () {
	if( updateCurrentPage() < ( pageCount - 1 ) ){
		goToPage( currentPage + 1 );
	}
}
function showPage( id, callback ) {
	activateJavaScript( id );
	$( '#page_' + id ).show();
	$( '#page_over_' + id ).fadeOut(pageOverFadeOutTime , function(){
		if( typeof( callback ) == 'function' ){
			callback();
		}
	});	
	pagesLoaded[id] = true;
}

function prewPage () {
	if( ( $( document ).scrollTop() % pageHeight ) == 0 ){
		if( updateCurrentPage() != 0 ){
			goToPage ( currentPage - 1 );
		} else {
			goToPage ( 0 );
		}
	} else {
		goToPage ( updateCurrentPage() );
	}
}
function checkPosition(){
	//if ( next_page_is_not_loaded && next_page_is_visible_in_screen && function_go_to_page_is_not_working )
	var temp = Math.floor( $(window).scrollTop() / pageHeight );
//	console.log('temp in checkposition = '+temp);
	updateCurrentPage();
	if ( ( typeof( pagesLoaded[ temp + 1 ] ) == 'undefined' ) && ( ( ( $(window).height() % pageHeight ) + $(window).scrollTop() ) > pageHeight ) && !goToPageInProgress ){
		showPage( temp + 1 );
	} else {
		//if ( page_is_not_loaded && function_go_to_page_is_not_working )
		if ( ( typeof( pagesLoaded[ temp ] ) == 'undefined' ) && ( !goToPageInProgress ) ) { // else if page is not loaded yet
			showPage( temp );
		}
	}
}
/* TOP BANNER STUFF */
var prevTopBanner = 0;
var topBannerRotationTime = 0;
var topBannerActionStack = [];
var topBannerAnimating = false;
function changeTopBannerTo( id, auto ){
	if( ( typeof auto === "boolean" ) && auto === true ){
	} else {
		stopTopBannersRotation();
		startTopBannersRotation( 10000 );
		trackEvent('what-is-smart','Banner','Change',id);
	}
	if( topBannerAnimating !== true ){
		if( prevTopBanner != id ){
			topBannerAnimating = true;
			$( '#page_0 .banners .banner_display img' ).unbind( 'load' ).load( function(){
				/* pagination */
				$( '#top_pagination_holder a.active' ).removeClass( 'active' );
				$( '#top_pagination_holder a' ).eq( id ).addClass( 'active' );
				/* end pagination */
				if ( topBannerActionStack.length > 0  ){
					var fadeOutTime = bannerSwitchFadeOutTime / 3;
				} else {
					var fadeOutTime = bannerSwitchFadeOutTime;
				}
				$( this ).fadeIn( fadeOutTime, function(){
					prevTopBanner = id;
					$( this ).parent().css('background-image','url("' + topBannerImages[id] + '")').children('img').hide( 0,function (){});
					topBannerAnimating = false;
					if( topBannerActionStack.length > 0 ){
						changeTopBannerTo( topBannerActionStack.shift(), false );
					}
				} );
			} ).attr( 'src' , topBannerImages[ id ] );
		} else {
			if( topBannerActionStack.length > 0 ){
				changeTopBannerTo( topBannerActionStack.shift(), false );
			}	
		}
	} else {
		topBannerActionStack.push( id );
	}
}
function changeTopBannerNext( auto ){
	if( topBannerImages.length > prevTopBanner + 1 ){
		changeTopBannerTo( prevTopBanner + 1, auto);
	} else {
		changeTopBannerTo( 0, auto );
	}
}
function startTopBannersRotation( timeout ){
	if( typeof timeout === 'undefined' ){
		var thisTime = bannerSwitchTimeOut;
	} else {
		var thisTime = timeout;
	}
	topBannerRotationTime = setTimeout( function(){
		if( topBannerRotationTime !== false ){
			changeTopBannerNext( true );
			startTopBannersRotation();
		}
	}, thisTime );
}
function stopTopBannersRotation(){
	clearTimeout( topBannerRotationTime );
	topBannerRotationTime = false;
}
function createTopPagination(){
	$.each( topBannerImages, function( index, src ){
		$( '#top_pagination_holder' ).append( $( document.createElement( 'a' ) ).click( function(){
			( function(){
				changeTopBannerTo( index );
			} )();
		} ) );				
		if( index === 0 ){
			$( '#top_pagination_holder a:first' ).addClass( 'active' );
		}
	});
	$( '#top_pagination_holder' ).append( $( document.createElement( 'div' ) ).addClass( 'clear' ) );
}
/* TOP BANNER STUFF END */
var headIsInPage = false;
var sliderAnimationTimeout ;
$.fn.stickyfloatObj = {};
$.fn.stickyfloatObj.opts = {};
$.fn.stickyfloatObj.scrollPanel = function (){
	if(  currentPage  != headIsInPage ){
			headIsInPage = currentPage;
			activateHeadMenuItem(headIsInPage);
			var newpos = ( headIsInPage * pageHeight ) + $.fn.stickyfloatObj.opts.offsetY;
			$.fn.stickyfloatObj.obj.stop(true,true);
			clearTimeout(sliderAnimationTimeout);
			sliderAnimationTimeout = setTimeout( function(){ $.fn.stickyfloatObj.obj.stop(true,true).animate({ top: newpos }, $.fn.stickyfloatObj.opts.duration, headerAnimationTypeUp );},headPanelDelayTime);
	}
};
var scrollTopPositionTemp = 0;
var scrollTopPositionReal = 0;
$.fn.stickyfloat = function(options) {
	$.fn.stickyfloatObj.obj = this;
	$.fn.stickyfloatObj.opts = $.extend({ startOffset: parseInt( this.parent().offset().top + parseInt(options.top) ), offsetY: parseInt(options.top), duration: 200, lockBottom:true }, options);
	this.offset( { 'top':'-' + this.height() + $.fn.stickyfloatObj.opts.offsetY } );
	this.css({ position: 'absolute' });
	if(options.center){
		this.css('left','50%').css({
			marginLeft:	'-' + ( this.outerWidth() / 2) + 'px',
			display: 'block'
		});
	}
	this.animate( { top: $.fn.stickyfloatObj.opts.startOffset }, $.fn.stickyfloatObj.opts.duration, headerAnimationTypeUp );
 
	
	$(window).scroll(function (e) {
//		console.log(e);
		if( !internalHashChange ){
//			supercount ++;
//			scrollTopPositionReal = scrollTopPositionTemp;
//			scrollTopPositionTemp = $(document).scrollTop(); 
//			console.log(supercount+'.) (OnScroll) '+scrollTopPositionTemp);
			//if( Math.abs( scrollTopPositionReal - scrollTopPositionTemp ) < 100 ){
//				console.log('checkPosition(); '+ document.location.hash);
				if( hackTimeout != 0 ){
					clearTimeout(hackTimeout);
				}
				hackTimeout = setTimeout( function(){
					hackTimeout = 0;
					checkPosition();
					$.fn.stickyfloatObj.scrollPanel();
				},100);
//				//updateHashHistory();
			//}
		}
	}); 
};
hackTimeout = 0;
//function updateHashHistory(){
//	hashHistory.push()
//	$.each( hashHistory, function( index,key ){
//		window.location.hash = key;
//	});
//}
//var supercount = 0;
var currentPortfolioPage = 0;
var currentPortfolioItem = 0;
function goToPortfolioItem( id ){
	updateHash( 'portfolio' , id );
	if ( currentPortfolioItem != id ){
		prevPortfolioItem = currentPortfolioItem;
		currentPortfolioItem = id;
		if ( currentPortfolioPage != 0 ){
			if( $('#portfolio_holder #itemNumber_' + prevPortfolioItem ).nextAll('#itemNumber_' + id).length > 0 ){
				//if site we are trying to show is in front
				var countedItems = 1;
				$('.why-go-smart .content_wrapper #why-go-smart_portfolio_item_' + prevPortfolioItem ).nextUntil('#why-go-smart_portfolio_item_' + id).each( function(){
					if( $( this ).is(':visible') ){
						countedItems ++;
					}
				});
				currentPortfolioPage += countedItems;
				currentPortfolioItem = id;
				$( '#why-go-smart_portfolio_item_' + id ).show(0,function(){
					$( '.why-go-smart .content_wrapper').animate({'margin-left': -984 * currentPortfolioPage }, 1000 ,function(){
						portfolioStartPhotos( id );
						portfolioLoadPhotoThumb( id , 2 );
						clearPortfolioItem();
					});
					$( '#why-go-smart_portfolio_item_' + id + ' .prev_item' ).css({'display':'block'});
					if( $('#portfolio_holder #itemNumber_' + id ).nextAll(':visible').length == 0 ){
						$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'none'});
					}else{
						$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'block'});
					}
				});
			} else {
	//			show back
				if ( $( '#why-go-smart_portfolio_item_' + id ).is(':hidden') ){
					currentPortfolioPage ++;
				}
				$( '#why-go-smart_portfolio_item_' + id ).show(0,function(){
					$( '.why-go-smart .content_wrapper').css({'margin-left': -984 * currentPortfolioPage })
					$( '#why-go-smart_portfolio_item_' + id + ' .button_next' ).css({'display':'block'});
					if( $('#portfolio_holder #itemNumber_' + id ).prevAll(':visible').length == 0 ){
						$( '#why-go-smart_portfolio_item_' + id + ' .button_prev' ).css({'display':'none'});
					} else {
						$( '#why-go-smart_portfolio_item_' + id + ' .button_prev' ).css({'display':'block'});	
					}
					var countedItems = 1;
					$('.why-go-smart .content_wrapper #why-go-smart_portfolio_item_' + prevPortfolioItem ).prevUntil('#why-go-smart_portfolio_item_' + id).each( function(){
						if( $( this ).is(':visible') ){
							countedItems ++;
						}
					});					
					currentPortfolioPage -= countedItems;
					currentPortfolioItem = id;
					$( '.why-go-smart .content_wrapper').animate({'margin-left': -984 * currentPortfolioPage }, 1000,function(){
						portfolioStartPhotos( id );
						portfolioLoadPhotoThumb( id , 2 );
						clearPortfolioItem();
					});	
				});			
			}
		} else {
			currentPortfolioPage = 1;		
			portfolioStartPhotos( id );
			$( '#why-go-smart_portfolio_item_' + id ).show();
			if( $('#portfolio_holder #itemNumber_' + id ).nextAll(':visible').length == 0 ){
				$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'none'});
			} else {
				$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'block'});
			}
			if( $('#portfolio_holder #itemNumber_' + id ).prevAll(':visible').length == 0 ){
				$( '#why-go-smart_portfolio_item_' + id + ' .prev_item' ).css({'display':'none'});
			} else {
				$( '#why-go-smart_portfolio_item_' + id + ' .prev_item' ).css({'display':'block'});	
			}
			$( '.why-go-smart .content_wrapper').animate({'margin-left':'-984px'},1000,function(){
				portfolioLoadPhotoThumb( id , 2 );
			});
		}
	}
	trackEvent('what-we-do','View Portfolio',portfolio_names[id]);
}
function backToPortfolio(){
	updateHash('portfolio','');
	stopSelfShowingImages();
	$( '.why-go-smart .content_wrapper').animate({'margin-left':'0px'},1000,function(){
		$( '.why-go-smart .portfolio_item_detail' ).hide();		
		$( '.portfolio_item_detail .pictures_holder_2 .picture_wrapper' ).empty();
		$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .pictures_holder_2' ).css( 'margin-left', '' ).find( '.first_bit' ).css('width','')
		currentPortfolioItem = 0;
		currentPortfolioPage = 0;
		prevPortfolioItem = 0;
	});
}
var prevPortfolioItem = 0;
function clearPortfolioItem( ){
	if( prevPortfolioItem != 0 ){
		stopSelfShowingImages();
		$( '#why-go-smart_portfolio_item_' + prevPortfolioItem + ' .picture_nav_wrapper .picture_wrapper').empty();
		$( '#why-go-smart_portfolio_item_' + prevPortfolioItem + ' .pictures_holder_2' ).css( 'margin-left', '' ).find( '.first_bit' ).css('width','');
	}
}

function portfolioItemNext(){
	stopPortfolioAnimation = true;
	prevPortfolioItem = currentPortfolioItem;
	currentPortfolioPage ++;
	var id = $('#portfolio_holder #itemNumber_' + currentPortfolioItem ).nextAll(':visible').eq(0).attr('id').substring(11);
	updateHash( 'portfolio', id );
	currentPortfolioItem = id;
	$( '#why-go-smart_portfolio_item_' + id ).show(0,function(){
		$( '.why-go-smart .content_wrapper').animate({'margin-left': -984 * currentPortfolioPage }, 1000 ,function(){
			stopPortfolioAnimation = false;
			clearPortfolioItem();
			portfolioStartPhotos( id );
			portfolioLoadPhotoThumb( id , 2 );
		});
	
		$( '#why-go-smart_portfolio_item_' + id + ' .prev_item' ).css({'display':'block'});
		if( $('#portfolio_holder #itemNumber_' + id ).nextAll(':visible').length == 0 ){
			$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'none'});
		}else{
			$( '#why-go-smart_portfolio_item_' + id + ' .next_item' ).css({'display':'block'});
		}
	});
	trackEvent('what-we-do','View Portfolio',portfolio_names[id]);
}
function portfolioItemPrev(){
	stopPortfolioAnimation = true;
	prevPortfolioItem = currentPortfolioItem;
	var id = $('#portfolio_holder #itemNumber_' + currentPortfolioItem ).prevAll(':visible').eq(0).attr('id').substring(11);
	updateHash( 'portfolio', id );
	if ( $( '#why-go-smart_portfolio_item_' + id ).is(':hidden') ){
		currentPortfolioPage ++;
	}
	$( '#why-go-smart_portfolio_item_' + id ).show(0,function(){
		$( '.why-go-smart .content_wrapper').css({'margin-left': -984 * currentPortfolioPage })
		$( '#why-go-smart_portfolio_item_' + id + ' .button_next' ).css({'display':'block'});
		if( $('#portfolio_holder #itemNumber_' + id ).prevAll(':visible').length == 0 ){
			$( '#why-go-smart_portfolio_item_' + id + ' .button_prev' ).css({'display':'none'});
		} else {
			$( '#why-go-smart_portfolio_item_' + id + ' .button_prev' ).css({'display':'block'});	
		}
		currentPortfolioPage --;
		currentPortfolioItem = id;
		$( '.why-go-smart .content_wrapper').animate({'margin-left': -984 * currentPortfolioPage }, 1000,function(){
			stopPortfolioAnimation = false;
			clearPortfolioItem();
			portfolioStartPhotos( id );
			portfolioLoadPhotoThumb( id , 2 );
		});	
	});
	trackEvent('what-we-do','View Portfolio',portfolio_names[id]);
}

var currentPB = 0;
var prevPB = 0;
var bannerAnimationStack = [];
var bannerDoingAnimation = false;
function PBGoTo( option, manual ){
	var nr ;
	switch(option){
		case 'next':
			(currentPB < 4)? nr = currentPB + 1 : nr = 0;
			break;
		case 'prev':
			(currentPB > 0)? nr = currentPB - 1 : nr = 4;
			break;
		default:
			nr = option;
	}
	if( ! bannerDoingAnimation  ){
		if( currentPB != nr){
			var wantedBannerPosition = $( '#procces_banner_' + nr ).position().left / ( 600 );
				var difference = Math.abs ( wantedBannerPosition );
				if( wantedBannerPosition < 0 ){
					for( var i = 0; i < difference; i++ ){
						$('.our_process_banners .wrapper').prepend( function(){return $(this).children(':last')} );
					}
				} else {
					for( var i = 0; i < difference; i++ ){
						$('.our_process_banners .wrapper').append( function(){return $(this).children(':first')} );
					}	
				}
			$('.our_process_banners .wrapper').css( {'margin-left': ( ( -696 * 2 )+( 696 * wantedBannerPosition  ) ) + 'px'} );
			bannerDoingAnimation = true;
			
			if( currentPB != 0 ){
				if( nr != 0 ){
					$('.our_process_panel div.special_div').eq( currentPB - 1 ).fadeIn('slow');
				}
			} else {
				$('.our_process_panel div.special_div').each(function(index){
					if( index !=  ( nr - 1 )  ){
						$(this).fadeIn('slow');
					}
				});				
			}
			
			if( nr != 0 ){
					$('.our_process_panel > div > .special_div').eq( nr - 1 ).fadeOut('slow');
			} else {
				$('.our_process_panel > div > .special_div').fadeOut('slow');
			}
			
			$('.our_process_banners .wrapper').animate({'margin-left': ( -696 * 2 ) + 'px' },'slow',function(){
				bannerDoingAnimation = false;
				currentPB = nr;
				if ( bannerAnimationStack.length > 0 ){
					PBGoTo( bannerAnimationStack.shift() );
				}
			});
		}
	}else{
		bannerAnimationStack.push(option);
	}
	if(typeof(manual) != 'undefined') {
		trackEvent('how-we-do-it','Section','Change',nr);
	}
}
function PBNext(manual){
	if(typeof(manual) != 'undefined') {
		PBGoTo('next',true);
	}
	else {
		PBGoTo('next');
	}
}
var selfSkippingBannersTimeoutId = false;
function startSelfSkippingBanners(){
	selfSkippingBannersTimeoutId = setTimeout(function(){
		PBNext();
		startSelfSkippingBanners();
	},bannersSwitchingTime3rdPage);
}
function delayBeforeStartingSelfSkippingBaners(){
	selfSkippingBannersTimeoutId = setTimeout(function(){
		startSelfSkippingBanners();
	}, bannersSwitchingTime3rdPageDelay);
}
function stopSelfSkippingBanners(){
	if ( selfSkippingBannersTimeoutId != false ){
		clearTimeout(selfSkippingBannersTimeoutId);
		selfSkippingBannersTimeoutId = false;
	}
}
function PBPrev(manual){
	if(typeof(manual) != 'undefined') {
		PBGoTo('prev',true);
	}
	else {
		PBGoTo('prev');
	}
}
function updateScrollBar(){
	if( $('#luv_list_page_3').height() > $('.luv_list_wrapper .list_wrapper').height() || parseInt( $('#foot_item_count').text() ) > 7 ){
		$( '.sliderWrapper' ).show();
	} else {
		$( '.sliderWrapper' ).hide();
	}	
}
function initiateCustumScrollBar(){
	$('.sliderVertical').slider({
		orientation: "vertical",
		range: "max",
		min: 0,
		max: 100,
		value: 100,
		slide: function(event, ui) {
			var difference = $('#luv_list_page_3').height() - $('.luv_list_wrapper .list_wrapper').height();
			var topValue = ((100-ui.value)*difference/100);
			$('.luv_list_wrapper .list_wrapper').scrollTop( topValue );//move the top up (negative value) by the percentage the slider has been moved times the difference in height
		}	
	});
	$('.luv_list_wrapper .list_wrapper').scroll( function() {
		var difference = $('#luv_list_page_3').height() - $('.luv_list_wrapper .list_wrapper').height();
		
		var top = 100 - (100/difference*$('.luv_list_wrapper .list_wrapper').scrollTop());
		
		$('.sliderVertical').slider( 'value', top );

	}); 		
}
function toggleFootExpand( callback, trackThis ){
	$('.foot_expand').slideToggle('slow',function(){
		if( $( this ).is(':visible') ){
			$( '#foot' ).focus();
			focusedOnFoot = true;
			if( typeof callback == 'function' )
				callback();
		}
	});
	$('#foot .foot_header .get_in_touch').toggleClass('down');
	if($('#foot .foot_header .get_in_touch').hasClass('down')) {
		if(typeof(trackThis) != 'undefined') {
			if(trackThis) {
				trackEvent('general','Get In Touch','View');
			}
		}
		else {
			trackEvent('general','Get In Touch','View');
		}
	}
}

var customPageBasket = function(){
		var self = this;
		self.basket = {};
		self.addI = function(el){
			var siteName = $(el).text('I').addClass('default').parents('.panel').find('.site_name').text();
			var itemId = $(el).parents('.item').attr('id');
			var id = parseInt(itemId.substring(11));
			$( '#why-go-smart_portfolio_item_' + id + ' .bottom_button_holder .portfolio_luv_this' ).addClass('active');
			if( typeof( self.basket[id] ) == 'undefined' ){
				self.basket[ id ] = siteName;
				$('#luv_list_page_3').prepend( $( document.createElement('div') ).append( $( document.createElement('div') ).addClass('site_name').text( siteName ).click( function(){ goToPortfolioItemFromAnywhere( id ) } ) )
																				 .append( $( document.createElement('div') ).addClass('remove').click(function(){self.removeI(id);}) ) 
						
						.attr('id', 'item_' + id + '_page_3').addClass('itemWrapper_page3') ) ;
				$('#foot_item_holder .foot_items_wrapper').prepend( 	
						$( '#foot_item_wrapper_template').clone().attr('id', 'item_' + id + '_foot')
						.find('.site_name').click( function(){ goToPortfolioItemFromAnywhere( id ); } ).text( siteName )
						.siblings('.remove').click( function(){self.removeI(id);})
						.parent().hide() 
				);
				toggleFootExpand(function(){
					$( '#item_' + id + '_foot').hide().show('slow'/*,function(){toggleFootExpand();}*/);
				},false);
				updateScrollBar();
				if( parseInt( $('#foot_item_count').text() ) == 0 ){
					$( '.foot_header .item_text_place' ).css('visibility','visible');
					$( '.empty_basket' ).css({display:'none'});
				}
				$('#foot_item_count').text( parseInt( $('#foot_item_count').text() ) + 1 );
				hideLuvTooltip();
				self.setCookie();
			}
			trackEvent('luv',portfolio_names[id]);
		};
		self.removeI = function(id){
			$( '#why-go-smart_portfolio_item_' + id + ' .bottom_button_holder .portfolio_luv_this' ).removeClass('active');
			delete self.basket[id];
			$( '#itemNumber_' + id +' .luv_this' ).removeClass('default').text('');
			$('#foot_item_count').text( parseInt( $('#foot_item_count').text() ) - 1 );
			$( '#item_' + id + '_foot').hide('slow',function(){
				$(this).remove();
				if(  parseInt( $('#foot_item_count').text() ) == 0 ) {
					$( '.foot_header .item_text_place' ).css('visibility','hidden');
					$( '.empty_basket' ).show('fast',function(){
						$( this ).css({display:'block'});
					});				
				}
				});
			$( '#item_' + id + '_page_3').hide('slow',function(){$(this).remove()});
			self.setCookie();
			updateScrollBar();
		};		
		self.clearItems = function(){
			for( key in self.basket ){
				self.removeI(key);
			}
		};
		self.setCookie = function(){
			var coockieString = '' ;
			for (var key in self.basket ){
				coockieString += key + '////=' + self.basket[key] + '////&';
			}
			setCookie( 'basket',coockieString.substring(0,coockieString.length-5) );
		};
		self.getCookie = function(){
			var coockieString = getCookie('basket');
			var itemCount = 0;
			if( coockieString != null && coockieString != ''){
				$( '.empty_basket' ).css({display:'none'});
				$( coockieString.split('////&') ).each( function(index,items){
					var item = items.split('////=');	//item[0]=id,item[1]=siteName	
					$('#luv_list_page_3').prepend( $( document.createElement('div') ).append( $( document.createElement('div') ).addClass('site_name').text( item[1] ).click( function(){ goToPortfolioItemFromAnywhere( item[0] ) } ) )
																					 .append( $( document.createElement('div') ).addClass('remove').click(function(){self.removeI(item[0]);}) ) 
																					 .attr('id', 'item_' + item[0] + '_page_3').addClass('itemWrapper_page3') ) ;					
					$('#foot_item_holder .foot_items_wrapper').append( 	
							$( '#foot_item_wrapper_template').clone().attr('id', 'item_' + item[0] + '_foot')
							.find('.site_name').click( function(){ goToPortfolioItemFromAnywhere( item[0] ) } ).text( item[1] )
							.siblings('.remove').click( function(){self.removeI(item[0]);} )
							.parent() 
					);					
					$( '#itemNumber_' + item[0] +' .luv_this' ).text('I').addClass('default');
					$( '#why-go-smart_portfolio_item_' + item[0] + ' .bottom_button_holder .portfolio_luv_this' ).addClass('active');
					self.basket[item[0]] = item[1] ;
					itemCount++;
				});
				$('#foot_item_count').text( itemCount );
				updateScrollBar();	
			}
		};
		self.unsetCookie = function(){
			unsetCookie('basket');
		};		
};
function customMouseScroller(id){
	$( '#'+id ).data('mousePositionY',0);
	$( '#'+id ).mouseleave( function(){ $(this).children(':first').stop(); $(this).data('mousePositionY',0)} );
	//objectOffsetTop = $('#'+id);
	var timmerPerPixMax = 40;
	var min_speedKoeficient = 0.25;
	var division = 9;
	var changeStep = 5;
	var layoutH = $( '#'+id ).height();	
	$( '#'+id ).mousemove( function( event ){
		var innerH 	= $( this ).children(':first').height();
		if(layoutH < innerH){
			var mousePostition = event.clientY - ( $(window).height() - 301 + this.offsetTop );
			length_from_center = Math.abs( mousePostition - ( layoutH / 2 ) );
			if( length_from_center > ( layoutH  / ( division * 2 ) ) ){
				if( length_from_center > ( $( this ).data('mousePositionY') + changeStep) || length_from_center < ( $( this ).data('mousePositionY') - changeStep) || $( this ).data('mousePositionY') == 0 ){
					
					$( this ).children(':first').stop();
					$( this ).data('mousePositionY',length_from_center);
					var mouse_travel = length_from_center - ( layoutH / ( division * 2 ) );
					var length_traveled = Math.abs( parseInt( $( this ).children(':first').css('margin-top') ) );				
					var mouse_travel_precent = 1 - ( ( mouse_travel * division ) / ( layoutH * 2 ) );
					if( mouse_travel_precent < min_speedKoeficient ){
						mouse_travel_precent = min_speedKoeficient;
					}
					if( mousePostition - ( layoutH / 2 ) < 0 ){//going up
						var newpos = 0;
						var speed = parseInt( mouse_travel_precent * timmerPerPixMax * length_traveled );
						$( this ).children(':first').animate( { 'margin-top': newpos+'px' }, speed, 'linear');
						
					}else{//going down
						var newpos = innerH - layoutH;
						var speed = parseInt( mouse_travel_precent * timmerPerPixMax * ( newpos - length_traveled ) );
						$( this ).children(':first').animate( { 'margin-top': -newpos+'px' }, speed, 'linear');
					}
				} else {
					//keep the animation don't do anything!!
				}
			}else{
				$( this ).children(':first').stop();
				$( this ).data('mousePositionY',0);
			}
		} else {
			$( this ).children(':first').stop();
			$( this ).data('mousePositionY',0);
		}
	});
}
//var LuvTooltipIn = 0;
function showLuvTooltip(el){
	var itemId = $('#LuvTooltip').data('itemId');
	if( typeof( luvBasket.basket[ parseInt( currentItem.substring(11) ) ]) == 'undefined'){
		if( ! ( $('#LuvTooltip').data( 'tooltipOut' )  &&  currentItem == itemId ) ){
			$('#LuvTooltip').data( 'tooltipIn' , setTimeout( function(){
				if( currentItem != itemId ){
					$('#LuvTooltip').data('itemId',currentItem).stop(true,true);
					clearTimeout( $('#LuvTooltip').data( 'tooltipIn' ) );
					clearTimeout( $('#LuvTooltip').data( 'tooltipOut' ) );
					$('#LuvTooltip').hide();
					$('#LuvTooltip').data( 'tooltipOut', '' );
					$('#LuvTooltip').data( 'tooltipIn', '' );
				}				
				$( '#LuvTooltip' ).css( { top : $(el).offset().top, left : $(el).offset().left} );
				$( '#LuvTooltip' ).data('tooltipIn' , '').fadeIn(toolTipFadeTime);
			}, toolTipFadeDelay ) );		
		} else {
			clearTimeout( $('#LuvTooltip').data( 'tooltipOut' ) );
			$('#LuvTooltip').data( 'tooltipOut', '' );
		}		
	}
}
function onLuvTooltip(el){
	var item = $( '#' + $('#LuvTooltip').data('itemId') ) ;
	showItemsPanel( item );
}
function hideLuvTooltip(){
	if( ! $('#LuvTooltip').data( 'tooltipIn' ) ){
		$('#LuvTooltip').data( 'tooltipOut' , setTimeout( function(){
			$( '#LuvTooltip' ).data('tooltipOut' , '').fadeOut( toolTipFadeTime , function(){
				$( this ).hide();
			});
		}, toolTipFadeDelay ) );		
	} else {
		clearTimeout( $('#LuvTooltip').data( 'tooltipIn' ) );
		$('#LuvTooltip').data( 'tooltipIn', '' );
	}	
}
function checkPageAndMove(){
	var page = getHash( 'page' );
	var portfolio = getHash( 'portfolio' );
	if( page ){
		if ( portfolio == null ){
			goToPage( page );
		} else {
			if ( page != currentPage ){
				goToPage( page , function(){
					setTimeout( function (){goToPortfolioItem( portfolio )},1000);
				});		
			} else {
				goToPortfolioItem( portfolio );
			}
		}
	}else{
		goToPage(0);
	}
}

function checkPageAndMoveHashChanged(){
	internalHashChange = false;
	var page = getHash( 'page' );
	var portfolio = getHash( 'portfolio' );
	console.log(portfolio);
	internalHashChange = false;
//	console.log(window.location.hash);
	if( page ){
		goToPageInProgress = true;
		$( window ).scrollTop( page * pageHeight );
//		console.log(window.location.hash);
		goToPageInProgress = false;
		if ( page != currentPage ){
			if ( portfolio != null ){
				goToPortfolioItem( portfolio );
			}
		} else {
			if ( portfolio != null ){
				goToPortfolioItem( portfolio );
			} else {
				if ( page == 1 ){
					backToPortfolio();
				}
			}
		}
	}else{
		$( window ).scrollTop( 0 );
	}
}

function openWindow( url, width, height ) {
	window.open( url, 'newWin','menubar=0,resizable=1,scrollbars=1,width='+width+',height='+height);
}
function openWindowShare( url, link, width, height ) {
	window.open( url + link, 'newWin','menubar=0,resizable=0,scrollbars=0,toolbar=0,titlebar=0,status=0,location=0,width='+width+',height='+height);
	trackEvent('what-we-do','Share Site',portfolio_names[currentPortfolioItem]);
}
var currentItem = 0;
function showShareTooltip(el){
	var itemId =  $( '#shareTooltip' ).data( 'itemId' );
	if( currentItem !== itemId ){
		resetShareTooltip();
		itemId =  currentItem;
	}
	if( ! $( '#shareTooltip' ).data( 'tooltipOut' ) ){
		$( '#shareTooltip' ).data( 'tooltipIn' , setTimeout( function(){
			//var url = $('.share .url', el).text();
			var url = serverName + '?' + pageNamesArray[ 1 ] + '--' + portfolio_names[ itemId.substring( 11, itemId.lenght ) ];
			$( '#shareTooltip' ).css( { top : $('.share', el).offset().top, left : $('.share', el).offset().left} );
			$( '#shareTooltip' ).data( 'tooltipIn','').fadeIn( toolTipFadeTime );
			$( '#shareTooltip .social_item' ).click(function(){
					openWindowShare( $(this).attr('href'), url, 700, 300  );
					return false;
				});
		} ,toolTipFadeDelay ) );
	} else {
		clearTimeout( $( '#shareTooltip' ).data( 'tooltipOut' ) );
		$('#shareTooltip').data( 'tooltipOut', '' );
	}
}
var portfolioShareItemId = 0;
function showShareTooltipPortfolio(){
	var itemId =  currentPortfolioItem;
	if( portfolioShareItemId != itemId ){
		$( '#shareTooltipPersonal' ).data( 'tooltipOut', '' );
	}
	portfolioShareItemId = itemId;
	if( ! $( '#shareTooltipPersonal' ).data( 'tooltipOut' ) ){
		$( '#shareTooltipPersonal' ).data( 'tooltipIn' , setTimeout( function(){
			//var url = $('.share .url', el).text();
			var url = serverName + '?' + pageNamesArray[ 1 ] + '--' + portfolio_names[ itemId ];
			$( '#shareTooltipPersonal' ).css( { top : $('#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .portfolio_share').offset().top, left : $('#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .portfolio_share').offset().left} );
			$( '#shareTooltipPersonal' ).data( 'tooltipIn','').fadeIn( toolTipFadeTime );
			$( '#shareTooltipPersonal .social_item' ).click(function(){
					openWindowShare( $(this).attr('href'), url, 700, 300  );
					return false;
				});
		} ,toolTipFadeDelay ) );
	} else {
		clearTimeout( $( '#shareTooltipPersonal' ).data( 'tooltipOut' ) );
		$('#shareTooltipPersonal').data( 'tooltipOut', '' );
	}
}
function addShareTooolTips(){
	$( '.portfolio_item_detail .portfolio_share, #shareTooltipPersonal' ).mouseenter(function(){
		showShareTooltipPortfolio();
	}).mouseleave(function(){
		hideShareTooltipPortfolio();
	});
}
function hideShareTooltipPortfolio(){
	if( ! $( '#shareTooltipPersonal' ).data( 'tooltipIn' )){
		$( '#shareTooltipPersonal' ).data( 'tooltipOut' ,setTimeout( function(){
			$( '#shareTooltipPersonal' ).data( 'tooltipOut','').fadeOut( toolTipFadeTime );
		} ,toolTipFadeDelay ) );		
	} else {
		clearTimeout( $( '#shareTooltipPersonal' ).data( 'tooltipIn' ) );
		$('#shareTooltipPersonal').data( 'tooltipIn', '' );		
	}
}

function hideShareTooltip(){
	if( ! $( '#shareTooltip' ).data( 'tooltipIn' )){
		$( '#shareTooltip' ).data( 'tooltipOut' ,setTimeout( function(){
			$( '#shareTooltip' ).data( 'tooltipOut','').fadeOut( toolTipFadeTime );
		} ,toolTipFadeDelay ) );		
	} else {
		clearTimeout( $( '#shareTooltip' ).data( 'tooltipIn' ) );
		$('#shareTooltip').data( 'tooltipIn', '' );		
	}
}
function resetShareTooltip(){
	$( '#shareTooltip' ).hide();
	$( '#shareTooltip' ).data( 'itemId', currentItem );
	$( '#shareTooltip' ).data( 'tooltipIn', '');
	$( '#shareTooltip' ).data( 'tooltipOut', '');
}
function onShareTooltip(el){
	var item = $( '#' + $('#shareTooltip').data('itemId') ) ;
	showItemsPanel( item );
	showShareTooltip( item );
}
function offShareTooltip(el){
	var item = $( '#' + $('#shareTooltip').data('itemId') ) ;
	hideItemPanel( item );
	hideShareTooltip( item );
}
function showItemsPanel(el){
	currentItem = $(el).attr('id');
	if ( $(el).data('hidding') ){
		clearTimeout( $(el).data('hiddingId') );
		$(el).data('hidding', false);
	} else {
		$(el).data('showing',true);
		$( '.panel',el ).stop().show().animate({height:'57px','margin-top':'-67px','padding-top':'10px'},showItemsPanelAnimationTime ,function(){ $( this ).data('showing',false); });
	}	
}
function hideItemPanel(el){
	$(el).data('hidding', true);
	$(el).data('hiddingId', setTimeout(function(){
			$(el).data('hidding',false);
			$( '.panel',el ).stop().animate({height:'0px','margin-top':'0px','padding-top':'0px'},showItemsPanelAnimationTime ,function(){$( this ).hide();} );
	},panelFadeDelay));
}
loadedPortfolioItems = {};
var portfolioItemImageLoaded = 1;
function portfolioStartPhotos( id ){
	portfolioItemImageLoaded = 1;
	if ( typeof( loadedPortfolioItems[ id ]) == "undefined" ){
		loadedPortfolioItems[ id ] = {};
	}		
	var itemCount = portfolio_item_image_folders[id]['imageCount'];
	loadedPortfolioItems[ id ]['itemCount'] = itemCount;
	loadedPortfolioItems[ id ]['currentImage'] = 1;
//		var div = 
//		var tempDiv = {};
//		for( var ia = 1; ia < itemCount + 1; ia++ ){
//			(function(){
//				var i = 1;
				$( '#why-go-smart_portfolio_item_' + id + ' .main_picture_wrapper .pictures_holder').empty();
				var tempDiv = $( document.createElement('div') ).addClass('wrapper');
				$( '#why-go-smart_portfolio_item_' + id + ' .picture_nav_wrapper .picture_wrapper').append( $( tempDiv ).append( $( document.createElement('img') ).click( function (){ loadPortfolioImage( 1 );} ).attr({ src: portfolio_item_image_folders[id]['folder'] + '/thumbs/' + 1 + '.jpg'}) ) );
//				if( i == 1){
					$( '#why-go-smart_portfolio_item_' + id + ' .main_picture_wrapper .pictures_holder').prepend( $( document.createElement('img') ).attr( {src:portfolio_item_image_folders[id]['folder'] + '/mains/' + 1 + '.jpg'} ).addClass('default') );
					if( typeof( portfolio_item_image_folders[ id ][ 'imageComment' ][ 1 ] ) != "undefined" ){
						var div =  $( document.createElement('div') ).addClass( 'transparent_dark_div' ).append(  $( document.createElement('div') ).addClass( 'inner_text' ).text( portfolio_item_image_folders[id][ 'imageComment' ][ 1 ][ 'text' ] ) );
						var indicator = $( document.createElement('div') ).addClass( 'portfolio_image_description_indicator' ).css('display','block');
						if( typeof( portfolio_item_image_folders[id][ 'imageComment' ][ 1 ][ 'head' ] ) == 'undefined' ){
							$( div ).prepend( $( document.createElement('div') ).addClass( 'inner_head' ).text( 'Image Information' ) );
						} else {
							$( div ).prepend( $( document.createElement('div') ).addClass( 'inner_head' ).text( portfolio_item_image_folders[id][ 'imageComment' ][ 1 ][ 'head' ] ) );
						}
						$( '#why-go-smart_portfolio_item_' + id + ' .main_picture_wrapper .pictures_holder').append( div ).append( indicator ).unbind().mouseenter( function(){
																																	showPictureInformation();
																																})
																																.mouseleave( function(){
																																	hidePictureInformation();
																																});						
					} else {
						var div =  $( document.createElement('div') ).addClass(' transparent_dark_div' ).append( $( document.createElement('div') ).addClass( 'inner_head' ) ).append(  $( document.createElement('div') ).addClass( 'inner_text' ) );
						var indicator = $( document.createElement('div') ).addClass( 'portfolio_image_description_indicator' );
						$( '#why-go-smart_portfolio_item_' + id + ' .main_picture_wrapper .pictures_holder').append( div ).append( indicator );	
					}
//				}else{
//					$( '#why-go-smart_portfolio_item_' + id + ' .main_picture_wrapper .pictures_holder').append( $(document.createElement('img') ).attr( {src:portfolio_item_image_folders[id]['folder'] + '/mains/' + i + '.jpg'} ) );
//				}
//			})();
//		}

}
function loadNextPortfolioItemImage(){
	
	if ( portfolioItemImageLoaded < portfolio_item_image_folders[ currentPortfolioItem ]['imageCount']){
		loadPortfolioImage( portfolioItemImageLoaded + 1, true );
	} else {
		loadPortfolioImage( 1, true );
	}
	
}
var selfShowingImagesTimeoutId = 0;
var SelfShowingImagesOn = false;
function startSelfShowingImages(){
	if ( SelfShowingImagesOn == false ){
		SelfShowingImagesOn = true;
		selfShowingImagesTimeoutId = setTimeout(function(){
			if( currentPortfolioItem != 0 ){
				loadNextPortfolioItemImage();
				SelfShowingImagesOn = false;
				startSelfShowingImages();
			} 
		}, 5000 );
	}
}
function stopSelfShowingImages(){
	clearTimeout(selfShowingImagesTimeoutId);
	SelfShowingImagesOn = false;
}
function portfolioLoadPhotoThumb( id , itemNr ){
	if( portfolio_item_image_folders[id]['imageCount'] >= itemNr ){
		( function(){
			var item = itemNr;
			var div = $( document.createElement('div') ).addClass('wrapper').css( 'display', 'none' );
			var image = new Image();
			// create container
			$( '#why-go-smart_portfolio_item_' + id + ' .picture_nav_wrapper .picture_wrapper').append( $( div ) ); 
			//add image to the container
			$( '#why-go-smart_portfolio_item_' + id + ' .picture_nav_wrapper .picture_wrapper .wrapper').eq( itemNr - 1 ).append( $( image ).click( function (){ loadPortfolioImage( item );} ).load(function(){
				//display the image container
				$( '#why-go-smart_portfolio_item_' + id + ' .picture_nav_wrapper .picture_wrapper .wrapper' ).eq( itemNr-1 ).fadeIn('fast',function(){
					if( !stopPortfolioAnimation ){
						portfolioLoadPhotoThumb(id, item + 1);											
					}
				});
			}).attr({ src: portfolio_item_image_folders[id]['folder'] + '/thumbs/' + item + '.jpg'}) );
		})();
	} else {
		if (!dontStartSelfShowingImages){
			startSelfShowingImages();
		}
	}
}
function portfolioLoadPhoto( id , item){
	
}
function portfolioNextImage(  ){
	if ( loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ] + 1 > loadedPortfolioItems[ currentPortfolioItem ]['itemCount'] - 6 ){
		//do nothing
	} else {	
		loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ] ++;
		$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .pictures_holder_2' ).animate( {'margin-left' : ( -111 * loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ]) + 'px' }, 'slow' );
	}
	
}
function portfolioPrevImage(  ){
	if ( loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ] - 1 < 0 ){
		//do nothing
	} else {
		loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ] --;
		$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .pictures_holder_2' ).animate( {'margin-left' : ( -111 * loadedPortfolioItems[ currentPortfolioItem ][ 'currentImage' ]) + 'px'}, 'slow' );
	}	
}
function showPictureInformation() {
	$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div' ).stop().animate({'bottom':'0'},'slow');
}
function hidePictureInformation() {
	$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div' ).stop().animate({'bottom':'-121'},'slow');	
}
function loadPortfolioImage( el , auto ){
	if( typeof auto == 'undefined' ){
		stopSelfShowingImages();
		startSelfShowingImages();
	}
	$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder' ).unbind();//.find( '.portfolio_image_description_indicator' ).fadeOut( 'slow' );
	var newSrc = portfolio_item_image_folders[ currentPortfolioItem ]['folder'] + '/mains/' + el + '.jpg';
	var img = new Image();
	if( typeof( portfolio_item_image_folders[ currentPortfolioItem ][ 'imageComment' ][ el ] ) != "undefined" ){
		$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder' )  .mouseenter( function(){
			showPictureInformation();
		})
		.mouseleave( function(){
			hidePictureInformation();
		});
		$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div' ).css('display','none');
		$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div .inner_text' ).text( portfolio_item_image_folders[currentPortfolioItem][ 'imageComment' ][ el ][ 'text' ] );
		if( typeof( portfolio_item_image_folders[currentPortfolioItem][ 'imageComment' ][ el ][ 'head' ] ) == 'undefined' ){
			$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div .inner_head' ).text( 'Image Information' );
		} else {
			$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div .inner_head' ).text( portfolio_item_image_folders[currentPortfolioItem][ 'imageComment' ][ el ][ 'head' ] );
		}
	} else {
		$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .portfolio_image_description_indicator' ).fadeOut( 'slow' );
	}
	$( img ).load(function(){
			$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .pictures_holder_2 .first_bit' ).animate( { 'width':  (  ( 111 * (el-1) ) + 48 ) + 'px'  }, 'slow' );
	//	var oldSrc = $( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder img' ).attr('src');
			$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder' ).css( {'background':'url(' + newSrc + ') no-repeat'} );
			
			if( typeof( portfolio_item_image_folders[ currentPortfolioItem ][ 'imageComment' ][ el ] ) != "undefined" ){
				$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .transparent_dark_div' ).fadeIn( 'slow' );
				$(  '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .portfolio_image_description_indicator' ).fadeIn( 'slow' );
			}
			
			$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder img' ).fadeOut( 'slow', function(){
				//$( this ).hide();
				$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder img' ).attr( 'src', newSrc ).load(function(){
					$( '#why-go-smart_portfolio_item_' + currentPortfolioItem + ' .main_picture_wrapper .pictures_holder img' ).show();
				});
				portfolioItemImageLoaded = el;
			});
	}).attr('src',newSrc);
}
function addToLoveBasketPortfolio(){
	luvBasket.addI( $( '#itemNumber_' + currentPortfolioItem + ' .tools .luv_this' ) );
}
/* popup stuff */

function netfoxGoToHeader( nr ){
	$('#netfox_detail_popup .headers_wrapper .active' ).removeClass('active');
	$('#netfox_detail_popup .headers_wrapper h3' ).eq( nr ).addClass('active');
	var offset1 = $('#netfox_detail_popup .overview h3').eq(nr).offset()
	var offset2 = $('#netfox_detail_popup .overview h3').eq(0).offset()
	var height =  offset1.top - offset2.top;
	$('#scrollbar1').tinyscrollbar_update( height );
}
vacancyOpened = false;
function showVacancy( el ){
	if ( vacancyOpened === false ) {
		vacancyOpened = true;
		var name = $( el ).parents( '.vacancy' ).prev().text();
		$( '#vacancies_detail_popup .bottomFormBit .vacancies_vacancy_name .actual_name_unique' ).text( name );
		$( '#vacancies_job_specification' ).val( name );
		$( '#vacancies_detail_popup .bottomFormBit .button.cancel' ).unbind('click').removeAttr('onclick').click( function(){
			hideVacancy( el );
		});
		$( el ).removeAttr('onclick').unbind('click');
		
		$( '#vacancies_detail_popup .insideWrapper' ).animate({'height':547},'slow',function(){
			$( el ).click( function(){
				hideVacancy( el );
			} ).find('.mid span').text('Cancel  ').parent().find('img').attr('src','custom/images/arrow_up.png');
		});	
	} else {
		$( '#vacancies_detail_popup .bottomFormBit .button.cancel' ).click();
		vacancyOpened = false;
		setTimeout( function () {$( el ).click();},500);
	}
}

function closeVacancies(){
	$('#vacancies_detail_popup').dialog('close');
	$('#vacancies_detail_popup .vacancy .button').unbind('click').removeAttr('onclick').click( function(){
		showVacancy( this );
	} ).find('.mid span').text('Enquire  ').parent().find('img').attr('src','custom/images/arrow_down.png');
	setTimeout( function (){ $( '#vacancies_detail_popup .insideWrapper' ).css( {'height':280} )},500 );
}

function hideVacancy( el ){
	$( '#vacancies_detail_popup .bottomFormBit .button.cancel' ).unbind('click');
	$( el ).unbind('click').click( function(){
		showVacancy( el );
	} ).find('.mid span').text('Enquire  ').parent().find('img').attr('src','custom/images/arrow_down.png');
	$( '#vacancies_detail_popup .insideWrapper' ).animate({'height':280},'slow');	
	vacancyOpened = false;
}
function sendVacanciesForm(form){
	var options = { 
		    target:     $('textarea', form), 
		    url:        '/email.php', 
		    success:    function( data ) { 
				if( data == '1' ){
					var name = $( 'input.firs_name', form ).val();
					$('input', form).each( function(){
						if( $(this).val() != '' )
							$(this).val('').blur();
					});
					closeVacancies();
					if( $('textarea', form).val() != '' )
						$('textarea', form).val('').blur();
					showCustomPopup('Thanks ' + name + ' for applying to this vacancy, we will contact you shortly<br/>Or you can call us on 0800 634 8600.','Thanks!');
					trackEvent( 'general', 'Vacancies form submitted' );
				}else{
					showCustomPopup('Something went wrong please try again later');
				}
		    } 
		}; 
		$( form ).ajaxSubmit( options );
}
function showCustomPopup( content, title ){
	if ( typeof(title) == 'undefined' ){
		title = 'Oops!';
	}
	$( '#customPopupHeader' ).text( title );
	$( '#customPopupContent' ).html( content );
	$( '#customPopupWrapper' ).dialog( 'open' );
}
function openPrivacyPolicy(){
	var head = "Privacy Policy";
	var content = '<p>TME Solutions Ltd is committed to protecting your privacy and maintaining the security of any personal information received from you. We strictly adhere to the requirements of the data protection legislation in the UK. The purpose of this statement is to explain to you what personal information we collect and how we may use it.<br /><br />When you make an enquiry, we need to know your name, contact details, email address and requirements. This allows us to process and fulfil your enquiry. You have the option to withhold personal information that is not required for the enquiry process.<br /><br />We use your personal information to update you about new products/services. We will only contact you with your consent.<br /><br />We do not sell, rent or exchange your personal information with any third party for commercial reasons, beyond the essential requirement.<br /><br />We follow strict security procedures in the storage and disclosure of information which you have given us, to prevent unauthorised access in accordance with the UK data protection legislation.<br /><br />We do not collect sensitive information about you except when you specifically knowingly provide it. In order to maintain the accuracy of our database, you can check, update or remove your personal details by contacting us at <a href="mailto:support@tmesolutions.co.uk">support@tmesolutions.co.uk</a>. We use a technology called "cookies" as part of a normal business procedure to track patterns of behaviour of visitors to our site. A cookie is an element of data that our Website sends to your browser which is then stored on your system. You can set your browser to prevent this happening. Any information collected in this way can be used to identify you unless you change your browser settings.<br /><br />If you have any questions about privacy please contact us at <a href="mailto:support@tmesolutions.co.uk">support@tmesolutions.co.uk</a></p>';
	showCustomPopupBig( content, head );
	trackEvent('general','Privacy Policy','View');
}
function openTermsConditions(){
	var head = "Terms & Conditions";
	var content = '<h4 class="first">1 ACCEPTANCE OF TERMS</h4><p>Your access to and use of TME Solutions Ltd (&quot;the Website&quot;) is subject exclusively to these Terms and Conditions. You will not use the Website for any purpose that is unlawful or prohibited by these Terms and Conditions. By using the Website you are fully accepting the terms, conditions and disclaimers contained in this notice. If you do not accept these Terms and Conditions you must immediately stop using the Website.</p><h4>2 ADVICE</h4><p>The contents of the Website do not constitute advice and should not be relied upon in making or refraining from making, any decision.</p><h4>3 CHANGES TO WEBSITE</h4><p>TME Solutions Ltd reserves the right to:<br />3.1 change or remove (temporarily or permanently) the Website or any part of it without notice and you confirm that TME Solutions Ltd shall not be liable to you for any such change or removal; and<br />3.2 change these Terms and Conditions at any time, and your continued use of the Website following any changes shall be deemed to be your acceptance of such change.</p><h4>4 LINKS TO THIRD PARTY WEBSITES</h4><p>The Website may include links to third party websites that are controlled and maintained by others. Any link to other websites is not an endorsement of such websites and you acknowledge and agree that we are not responsible for the content or availability of any such sites.</p><h4>5 COPYRIGHT</h4><p>5.1 All copyright, trade marks and all other intellectual property rights in the Website and its content (including without limitation the Website design, text, graphics and all software and source codes connected with the Website) are owned by or licensed to TME Solutions Ltd or otherwise used by TME Solutions Ltd as permitted by law.<br />5.2 In accessing the Website you agree that you will access the content solely for your personal, non-commercial use. None of the content may be downloaded, copied, reproduced, transmitted, stored, sold or distributed without the prior written consent of the copyright holder. This excludes the downloading, copying and/or printing of pages of the Website for personal, non-commercial home use only.</p><h4>6 DISCLAIMERS AND LIMITATION OF LIABILITY</h4><p>6.1 The Website is provided on an &quot;AS IS&quot; and &quot;AS AVAILABLE&quot; basis without any representation or endorsement made and without warranty of any kind whether express or implied, including but not limited to the implied warranties of satisfactory quality, fitness for a particular purpose, non-infringement, compatibility, security and accuracy.<br />6.2 To the extent permitted by law, TME Solutions Ltd will not be liable for any indirect or consequential loss or damage whatever (including without limitation loss of business, opportunity, data, profits) arising out of or in connection with the use of the Website.<br />6.3 TME Solutions Ltd makes no warranty that the functionality of the Website will be uninterrupted or error free, that defects will be corrected or that the Website or the server that makes it available are free of viruses or anything else which may be harmful or destructive.<br />6.4 Nothing in these Terms and Conditions shall be construed so as to exclude or limit the liability of TME Solutions Ltd for death or personal injury as a result of the negligence of TME Solutions Ltd or that of its employees or agents.</p><h4>7 INDEMNITY</h4><p>You agree to indemnify and hold TME Solutions Ltd and its employees and agents harmless from and against all liabilities, legal fees, damages, losses, costs and other expenses in relation to any claims or actions brought against TME Solutions Ltd arising out of any breach by you of these Terms and Conditions or other liabilities arising out of your use of this Website.</p><h4>8 SEVERANCE</h4><p>If any of these Terms and Conditions should be determined to be invalid, illegal or unenforceable for any reason by any court of competent jurisdiction then such Term or Condition shall be severed and the remaining Terms and Conditions shall survive and remain in full force and effect and continue to be binding and enforceable.</p><h4>9 GOVERNING LAW</h4><p>These Terms and Conditions shall be governed by and construed in accordance with the law of England and you hereby submit to the exclusive jurisdiction of the English courts.</p>';
	showCustomPopupBig( content, head );
	trackEvent('general','Terms And Conditions','View');
}
function showCustomPopupBig( content, title ){
	if ( typeof(title) == 'undefined' ){
		title = 'Oops!';
	}
	$( '#customPopupHeaderBig' ).text( title );
	$( '#customPopupWrapperBig .popup_content' ).html( content );
	$( '#customPopupWrapperBig' ).dialog( 'open' );
}
function trackEvent(category,action,label,value) {
	try{
		if(typeof(label) != 'undefined') {
			if(typeof(value) != 'undefined') {
				pageTracker._trackEvent(category,action,label,value);
			}
			pageTracker._trackEvent(category,action,label);
		}
		else {
			pageTracker._trackEvent(category,action);
		}
	}
	catch(err) {}
}
function visitSite() {
	trackEvent('what-we-do','Visit Site',portfolio_names[currentPortfolioItem]);
}
/* popup stuff end */
var luvBasket; 
function activateJavaScript( id ){
	id = parseInt(id);
	switch(id){
		case 0:
			createTopPagination();
			startTopBannersRotation();
			break;
		case 1:
			$('#portfolio_wrapper').createSlider({pagination:'#portfolio_nav_wrapper', itemFadeTime : webpagesSliderItemFadingAnimationTime});
			$('#portfolio_wrapper .addLuvTooltip').mouseenter(function(){ showLuvTooltip(this); })
			  .mouseleave(function(){ hideLuvTooltip();});
			$('#portfolio_wrapper .addShareTooltip').mouseenter(function(){ showShareTooltip( $( this ).parents('.item') ); })
				.mouseleave(function(){ hideShareTooltip(); });
			$('#shareTooltip').mouseleave( function(){ offShareTooltip(this);} )
				.mouseenter( function(){ onShareTooltip(this); } );
			$('#LuvTooltip').mouseenter( function(){ onLuvTooltip(this); } );
			addShareTooolTips();
			break;
		case 2:
			$( '.how_we_do_it .right_holder' ).mouseenter(function(){
												stopSelfSkippingBanners();
											}).mouseleave(function(){
												delayBeforeStartingSelfSkippingBaners();
											});
			startSelfSkippingBanners();
			break;
		case 3:
			initiateCustumScrollBar();
			updateScrollBar();
			break;
		default:
			break;
	}
}
//on load
var focusedOnFoot = false;
$( function () {
	if($.browser.msie){
		//toolTipFadeDelay = 0;
		webpagesSliderItemFadingAnimationTime = 0;
		toolTipFadeTime = 0;
		//alert('IE');
	}
	checkPageAndMove();
	$('#menu').stickyfloat({ duration: headSlidingPanelAnimationTime , center:true, top: '9'});
	customMouseScroller('foot_item_holder');
	var itemNumber = 1;
	$('#portfolio_wrapper .item').each(function(){
		var temp = itemNumber;
		var tempthis = this;
		$('.portfolio_image_wrapper_for_item', this).click(function(){
			goToPortfolioItem(temp);
		});
		$( '.panel', this ).click(function(){
			goToPortfolioItem(temp);
		}).find('.tools > a').click( function(e){
			 e.stopPropagation();
		});
		
		$( tempthis ).attr( 'id','itemNumber_' + temp ).mouseenter(function(){
			showItemsPanel( this );
		}).mouseleave(function(){
			hideItemPanel( this );
		})
		.find('.tools .detail').click(function(){
			goToPortfolioItem(temp);
		})
		;
		itemNumber++;
	});
	$( '.check_for_blur' ).each( function(){
		$( this ).removeClass('check_for_blur') .focus(function(){toggleBlur( this );})
												.blur(function(){toggleBlur( this );});
		toggleBlur( this );
	});
	$( 'div.checkbox' ).each( function(){ 
		$( this ).click( function(){ toggleCheckbox( this ); } )
		if( $('input',this).is(':checked') ){
			toggleCheckbox( this );			
		}
	});
	$('#foot').live( 'focusout', function(){ 
		if( $('.foot_expand').is(':visible') ) {
			focusedOnFoot = false;
			setTimeout(function(){;
				if( !focusedOnFoot ){
					toggleFootExpand();
				}
				//focusedOnFoot = false;
			},50);
		}
	});
	$('#foot').live( 'focusin', function(el){ if( $('.foot_expand', this).is(':visible') )focusedOnFoot = true; } );
	luvBasket = new customPageBasket;
	luvBasket.getCookie();
	
	$('#netfox_detail_popup').dialog({ 
		dialogClass: 'netfox_detail_popup',
		title: null,
		autoOpen: false,
		draggable: false,
		resizable: false,
		hide:true,
		modal:true,
		stack: false,
		show: 'show',
		width: 749,
		height: 'auto',
		open: function(event,data){
			$('#scrollbar1').tinyscrollbar_update();
		},
		close: function(event,data){
			$('#netfox_detail_popup .headers_wrapper .active' ).removeClass('active');
			$('#netfox_detail_popup .headers_wrapper h3' ).eq( 0 ).addClass('active');
		}		
	});	
	$('#scrollbar1').tinyscrollbar({ size: 465 });

	$('#vacancies_detail_popup').dialog({ 
		dialogClass: 'vacancies_detail_popup',
		title: null,
		autoOpen: false,
		draggable: false,
		resizable: false,
		hide:true,
		modal:true,
		stack: false,
		show: 'show',
		width: 765,
		height: 547,
		open: function(event,data){
			$('#scrollbar2').tinyscrollbar_update();
		},
		close: function(event,data){
			//$('#netfox_detail_popup .headers_wrapper .active' ).removeClass('active');
			//$('#netfox_detail_popup .headers_wrapper h3' ).eq( 0 ).addClass('active');
		}		
	});	
	$('#scrollbar2').tinyscrollbar({ size: 205 });
	$('#customPopupWrapper').dialog({ 
		dialogClass: 'vacancies_detail_popup',
		title: null,
		autoOpen: false,
		draggable: false,
		resizable: false,
		hide:true,
		modal:true,
		stack: false,
		show: 'show',
		width: 477,
		height: 'auto',
		zIndex: 1100,
		close: function(event,data){
			if( $('.foot_expand').is(':visible') ){
				$( '#foot' ).focus();
				focusedOnFoot = true;
				$('#foot').live( 'focusout', function(){ 
					if( $('.foot_expand').is(':visible') ) {
						focusedOnFoot = false;
						setTimeout(function(){
							if( !focusedOnFoot ){
								toggleFootExpand();
							}
						},50);
					}
				});
			}
		}
	});		
	
	$('#scrollbar3').tinyscrollbar({ size: 465 });
	$('#customPopupWrapperBig').dialog({ 
		dialogClass: 'customPopupWrapperBig',
		title: null,
		autoOpen: false,
		draggable: false,
		resizable: false,
		hide:true,
		modal:true,
		stack: false,
		show: 'show',
		width: 750,
		height: 'auto',
		open: function(event,data){
			$('#scrollbar3').tinyscrollbar_update();
		}
	});	
	
	$('.cv_input_wrapper').mouseenter( function(){
		$( this ).mousemove(function(event){
			var length = - ( 175 + $('.cv_input_wrapper').offset().left - event.pageX );
			$('.cv_input_wrapper input').css( 'margin-left', length );
		});
	}).mouseleave(function(){
		$( this ).unbind('mousemove');
	});
	// portfolio main picture auto showing stuff feature
	$( '.main_picture_wrapper .pictures_holder' ).live('mouseenter',function(){
		dontStartSelfShowingImages = true;
		stopSelfShowingImages();
	}).live('mouseleave',function(){
		dontStartSelfShowingImages = false;
		startSelfShowingImages();
	});
	$( window ).bind('hashchange', function() {
		 if ( !internalHashChange ){
//			 console.log('hash first');
//			 console.log('begin with hash = '+window.location.hash);
//			 counteris++;
//			 console.log( counteris + ' = '  + $( window ).scrollTop() );
			 checkPageAndMoveHashChanged();
		 } else {
			 internalHashChange = false;  
		 }
	});
	//gapi.plusone.go();
});
var counteris = 0;
