// copyright 2010 Refresh Mobile Ltd

// Add class to HTML for JavaScript specific styles
$('html').addClass('js');

// General site Feature Boxes
function featureBoxJs() {
	
	if($('.featureItem').size() > 1) {
		
		if($('.featureBoxWrap').length == 0) {
	
			// Feature Box setup
			scrollSpeed = 1000;
			
			var wrapClass = 'featureBoxWrap';
			
			$('.featureBox').wrap('<div class="' + wrapClass + '"></div>').after('<div><a href="#" class="next">Next</a><a href="#" class="previous">Previous</a></div><div class="featureBoxLinks"></div>');
			$('.featureBox').each( function() {
				$(this).find('.featureItems').width(($(this).width()) * $(this).find('.featureItem').size());
				for(i=1;i<=$(this).find('.featureItem').size();i++){
					$(this).parent().find('.featureBoxLinks').append('<a href="#" class="featureBoxLink">'+i+'</a> ');
				}
				
				//Set Next Previous position to half feature height
				var nextTop = Math.round(($(this).height() - $(this).parent().find('a.next').height()) /2);
				$(this).parent().find('a.next, a.previous').css('top',nextTop+'px');

			});
		
			$(".featureBoxLink:contains('1')").addClass('active');
			
			
			// If background change setup
			if($('.featureBox.backgroundChange').length > 0) {
				$('body').prepend('<div id="imageCacheFeatureBox" style="position: absolute; top: 0; left: -9999px; width: 10px; height: 10px;"></div>');
				$('.featureItem').each( function(i) {
					$('#imageCacheFeatureBox').append('<span class="featureItemBackground'+(i+1)+'">&nbsp;</span>');
				});
			}
			
			$('.featureItemAnnex1').addClass('active');

			
			// Run through once
			//featureBoxScrollOnce(scrollSpeed, 2000);
		
		}
	
		// Feature Box actions
		$('.featureBoxWrap a.next, .featureBoxWrap a.previous, .featureBoxWrap .featureBoxLink').click( function() {
			
			if($(this).hasClass('next')) {
				scrollDestination = $(this).parent().parent().find('.featureBoxLink.active').text();
				scrollDestination++;
				if(scrollDestination > $(this).parent().parent().find('.featureBoxLink:last').text()){
					scrollDestination = 1;
				}
			} else if($(this).hasClass('previous')) {
				scrollDestination = $(this).parent().parent().find('.featureBoxLink.active').text();
				scrollDestination--;
				if(scrollDestination <= 0){
					scrollDestination = $(this).parent().parent().find('.featureBoxLink:last').text();
				}
			} else {
				scrollDestination = $(this).text();
			}
				
			scrollDestinationPx = (scrollDestination-1) * $(this).parent().parent('.featureBoxWrap').find('.featureBox').width() +'px';
			$(this).parent().parent('.featureBoxWrap').find('.featureBox').scrollTo(scrollDestinationPx, scrollSpeed, {axis:'x'});
	
			$(this).parent().parent().find('.featureBoxLink').removeClass('active');
			$(this).parent().parent().find(".featureBoxLink:contains('"+scrollDestination+"')").addClass('active');
			
			// Background change if set
			if($(this).parent().parent().find('.featureBox.backgroundChange').length > 0) {
				$('#background').fadeOut('slow', function() {
					$('#background').removeClass().addClass('featureItemBackground'+scrollDestination);
				}).fadeIn('slow');
			}
			
			// If feature annex
			$('.featureItemAnnex').removeClass('active');
			$('.featureItemAnnex'+scrollDestination).addClass('active');
			
			
			$(this).blur();
			return false;
		});
		
		
		if($('.featureItemAnnex').length > 0){
		
			$('.featureItemAnnex').css('cursor','pointer');
			$('.featureBoxLinks').hide();
		
		}
			
		$('.featureItemAnnex').click( function() {
			
			// Last char in class should be frame number (the first frame is 1, not 0)
			scrollDestination = $(this).attr('class').substr($(this).attr('class').length-1,1);

			$('.featureItemAnnex').removeClass('active');
			$(this).addClass('active');
			
			
			// If not 'e' for active
			if(scrollDestination != 'e'){
						
				scrollDestinationPx = (scrollDestination-1) * $('.featureBoxWrap:first').find('.featureBox').width() +'px';
				$('.featureBoxWrap:first').find('.featureBox').scrollTo(scrollDestinationPx, scrollSpeed, {axis:'x'});
		
				$('.featureBoxWrap:first').find('.featureBoxLink').removeClass('active');
				$('.featureBoxWrap:first').find(".featureBoxLink:contains('"+scrollDestination+"')").addClass('active');
				
				// Background change if set
				if($(this).parent().parent().find('.featureBox.backgroundChange').length > 0) {
					$('#background').fadeOut('slow', function() {
						$('#background').removeClass().addClass('featureItemBackground'+scrollDestination);
					}).fadeIn('slow');
				}
				
			}
			
		});
			
		
	
	} else {
		$('.featureBox').wrap('<div class="featureBoxWrap"></div>');
	}
}



// Cycle the first .featureBox on the page all the way through once 
function featureBoxScrollOnce(scrollSpeed , pauseTime) {
		
		sequenceTime = (pauseTime + scrollSpeed) *  $('.featureBoxWrap:first').find('.featureItem').size();
		
		for(i=1;i<=($('.featureBoxWrap:first').find('.featureItem').size());i++){
			if(i == $('.featureBoxWrap:first').find('.featureItem').size()) {
				$('.featureBox:first').delay(pauseTime).scrollTo('0px', scrollSpeed, {axis:'x'});
			} else {
				$('.featureBox:first').delay(pauseTime).scrollTo(($('.featureBox:first').width())*i +'px', scrollSpeed, {axis:'x'});
			}
		}
		$('.featureBoxWrap:first').find('.next, .previous, .featureBoxLink').hide().delay(sequenceTime+500).fadeIn('slow');
		
}



function featureBoxGallery(){
	
	if($('.featureBox.gallery').length > 0){
	
		var designScreensPopupHTML = ['<div id="designScreensVeil"> </div>',
		                      	    '<div id="designScreensPopup">',
		                      	    '  <div id="designScreensPopupInner"><img src="" /></div>',
		                      	    '  <a class="previous" href="#"></a><a class="next" href="#"></a>',
		                      	    '  <div class="closePopup"><a href="#" class="close">Close</a></div>',
		                      	    '</div>'
		                      	   ].join('\n');	
		$('body').append(designScreensPopupHTML);
		
	
		
		
		// gallery screens pop up
		$('.featureBox.gallery a').click(function() {
	
			// active link
			$('.featureBox.gallery a').removeClass('active');
			$(this).addClass('active');
			
			// check heights and offset popup
			var minWindowH = 600; //px
			var topOffset = -80; //px
			
			// where on page Y
			var ScrollTop = document.body.scrollTop;
			if (ScrollTop == 0)	{
			    if (window.pageYOffset)
			        ScrollTop = window.pageYOffset;
			    else
			        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			}
			
			// update image
			$('#designScreensPopupInner img').attr('src', $(this).attr('href'));
			
			// is window big enough to fit popup?
			if( $(window).height() > minWindowH ){
				$('#designScreensPopup').css('position','fixed').css('top', 50+'px' );
			} else {
				$('#designScreensPopup').css('position','absolute').css('top', ScrollTop+topOffset+'px' );
			}
			
			$('#designScreensVeil').show();
			$('#designScreensPopup').fadeIn();
			
			$(this).blur();
			return false;
			
		});
		
		var animationInProgress = false;
		// design screens popup next/prev
		$('#designScreensPopup .previous, #designScreensPopup .next').click(function () {
			if(animationInProgress == false) {
				animationInProgress = true;
				$('#designScreensPopupInner img').addClass('currentImg');
				// position of <a> in featureItem + (position of featureItem * amount of <a> per featureItem)
				var index = $('.featureBox.gallery a.active').prevAll().length + ($('.featureBox.gallery a.active').parent().prevAll().length * $('.featureBox.gallery .featureItem:first a').length);

				if($(this).hasClass('next')) {
					$('#designScreensPopupInner').addClass('next');
					if(index == $('.featureBox.gallery a').length - 1) {
						index = 0;
					} else {
						index = index + 1;
					}			
				} else {
					$('#designScreensPopupInner').addClass('previous');
					if(index == 0) {
						index = $('.featureBox.gallery a').length - 1;
					} else {
						index = index - 1;
					}
				}
				
				// active link
				$('.featureBox.gallery a.active').removeClass('active');
				$('.featureBox.gallery a:eq('+index+')').addClass('active');
				$('.featureBoxLinks .featureBoxLink:eq(' + Math.floor(index / $('.featureBox.gallery .featureItem:first a').length) + ')').trigger('click');
				
				// update image
				var imageSrc = $('.featureBox.gallery a.active').attr('href');
				$('#designScreensPopupInner').append('<img src="'+imageSrc+'" class="newImg" alt="">');

				var newImage = new Image()
				newImage.onload = function(){
				
					// css animation triggered with classes
					setTimeout(function() {
						$('#designScreensPopupInner').addClass('animate');
						setTimeout(function() {
							$('#designScreensPopupInner .currentImg').remove();
							$('#designScreensPopupInner img').removeClass();
							$('#designScreensPopupInner').removeClass();
							animationInProgress = false;
							
				            // remove event and self to prevent IE on animated gif loops and clear up garbage.
							newImage = newImage.onload = newImage.onabort = newImage.onerror = null;
						},600);
					},200);
				
				}
				newImage.src = imageSrc;
			}
			$(this).blur();
			return false
		});
		
		// design screens popup close
		$('#designScreensPopup .close, #designScreensVeil').click( function() {
			$('.featureBox.gallery a').removeClass('active');
			$('#designScreensPopup, #designScreensVeil').fadeOut();
			$(this).blur();
			return false;
		});	
	}
	
}




function backgroundMove() {
	$('#container').css('position', 'relative');
	$(document).bind('mousemove',function(e){ 
        percentX = (e.pageX / $(window).width()) * 100;
        percentY = (e.pageY / $(window).height()) * 100;
        
        backgroundPercentX = ((percentX) / 1) * -1;
        backgroundPercentY = ((percentY) / 1) * -1;
        
        containerPercentX = (percentX-50)/5;
        containerPercentY = (percentY-50)/5;
        
        $('#background').css('background-position', backgroundPercentX + 'px ' + backgroundPercentY + 'px');
        
        $('#container').css('top', containerPercentY + 'px');
        $('#container').css('left', containerPercentX + 'px');
        
        $('#emulator-inner').css('top', containerPercentY*3 + 'px');
        $('#emulator-inner').css('left', containerPercentX*3 + 'px');

	});	
}




function emulatorSetup() {
	$('#body').before('<div id="imageCache"><span class="imageCache1"></span><span class="imageCache2"></span><span class="imageCache3"></span><span class="imageCache4"></span><span class="imageCache5"></span></div>');
	
	$('.launchEmulator').click( function() {
		$('#portalEmulator iframe').attr('src',$(this).attr('href'));
		$('#portalEmulator a.home').attr('href',$(this).attr('href'));
		$('#portalEmulator').removeClass().addClass($(this).attr('class')).show().draggable();
		$(this).blur;
		return false;
	});
	$('#portalEmulator .close').click( function() {
		$('#portalEmulator').hide();
		$(this).blur;
		return false;
	});
	$('#portalEmulator .back').click( function() {
		window.history.back();
		$(this).blur;
		return false;
	});
	
}



function messageSetup() {
	for(i=0;i<$('.message').size();i++) {
		$('#body').after(
			"\n<div class=\"popup\" id=\""+$('.message:eq('+i+')').attr('id')+"\">\n" +
			"  <div class=\"popup-inner\">\n" + $('.message:eq('+i+')').html() + 
			"<div><a href=\"#\" class=\"linkButton close\">Close</a></div>" +
			"\n  </div>\n</div>\n\n"
		);
	}
	
	$('.message').remove();
	
	$('.popup').hide();
	
	$('a.messageLink').click( function() {
		$('.popup').hide();
		$('.popup'+$(this).attr('href')).show().draggable();
		$('.popup').css('cursor','move');
		$(this).blur();
		return false;
	});
	
	$('.popup .close').click( function() {
		$('.popup').hide();
		$(this).blur();
		return false;
	});
}



$(document).ready(function(){

	featureBoxJs();
	
	featureBoxGallery();
	
	//backgroundMove();
	
	emulatorSetup();
	
	messageSetup();
	
//	$('.featureItemAnnex').mouseover( function() {
//		$('.featureItemAnnex').removeClass('active');
//		$(this).addClass('active');
//	});


});
