/*
 * ============================================================================
 * 
 * Copyright (c) Zennaware GmbH, 2010
 * All Rights Reserved.
 * 
 * ============================================================================
 */

var selectedMenuFeatureIndex = null;

var screenshotGroups = {
	 'overview':0, 
	 'merge':2, 
	 'diff':3, 
	 'history':6, 
	 'annotations':8, 
	 'transcript':9,
	 'externals':10,
	 'cloud':11,
	 'pending':12,
	 'config':13,
	 'props':14
	};

var screenshots = [
	{'href': 'screenshots/1.jpg',
   'title': 'Working Copy Browser',
   'description': 'The Working Copy Browser gives you an instant overview of the status of all the files in your working copy.'
	},
  
  {'href': 'screenshots/2.jpg',
   'title': 'Committing Changes',
   'description': "Because text comparison is built right into the application you can review changes and write log messages side by side."
  },
  
  {'href': 'screenshots/3.jpg',
   'title': 'Merging',
   'description': 'With support for a whole range of merging strategies, the Working Copy Checklist and the Change Preview, merging has never been easier.'
  },
  
  {'href': 'screenshots/4.jpg',
   'title': 'Differences',
   'description': 'Cornerstone\'s class-leading text comparison comes loaded with options including line differences, invisibles and annotations.'
  },
  
  {'href': 'screenshots/5.jpg',
   'title': 'Editing',
   'description': 'Not only can you review changes in Cornerstone but you can edit them as well. And of course, any changes you make can be undone.'
  },
  
  {'href': 'screenshots/6.jpg',
   'title': 'Image Differences',
   'description': "With super-fast image comparison built right in, there's no need to leave the comfort of Cornerstone."
  },
  
  {'href': 'screenshots/7.jpg',
   'title': 'Log',
   'description': "The Log shows your repository's history as a list of revisions and includes the log message and a list of the files changed."
  },
  
  {'href': 'screenshots/8.jpg',
   'title': 'Timeline',
   'description': 'You can browse through the history of any file, find branch points and even compare the histories of multiple files at once.'
  },
  
  {'href': 'screenshots/9.jpg',
   'title': 'Annotations',
   'description': 'Click a block of text to get not just the Who?, but also the When? and the Why? of the revision that contributed those lines.'
  },
  
  {'href': 'screenshots/10.jpg',
   'title': 'Transcript',
   'description': 'The transcript reveals the progress and outcome of operations such as imports, check outs, updates and commits.'
  },
  
  {'href': 'screenshots/11.jpg',
   'title': 'Externals',
   'description': "Cornerstone's dedicated editor simplifies working with externals, replacing tricky syntax with simple fields."
  },
  
  {'href': 'screenshots/12.jpg',
   'title': 'Cloud Services',
   'description': "We've partnered with Beanstalk and Codesion to make connecting to your hosted repositories super-easy."
  },
  
  {'href': 'screenshots/13.jpg',
   'title': 'Pending Updates',
   'description': "You'll always know how many updates are waiting for you in the repository because Cornerstone shows them right next to your working copy."
  },
  
  {'href': 'screenshots/14.jpg',
   'title': 'Configuration',
   'description': "Cornerstone's Subversion preference pane will take the 'rocket' out of 'rocket science' so you can easily harness the full power of Subversion."
  },
  
  {'href': 'screenshots/17.jpg',
   'title': 'User Properties',
   'description': 'Attach user properties such as text and files to items under version control.'
  }
];

/*
 * ============================================================================
 *
 * Preload image resources related to popovers to ensure smooth display without loading delays
 *
 * ============================================================================
*/

var popoverArrowImage = new Image(); popoverArrowImage.src = 'images/popover-arrow.png';
var blueUiPopoverArrowImage = new Image(); blueUiPopoverArrowImage.src = 'images/up-arrow-darkblue.png';
var greyUiPopoverArrowImage = new Image(); greyUiPopoverArrowImage.src = 'images/up-arrow-darkgrey.png';
var blamePopoverLeftImage = new Image(); blamePopoverLeftImage = 'images/blame-popover-left.png';
var blamePopoverMiddleImage = new Image(); blamePopoverMiddleImage = 'images/blame-popover-middle.png';
var blamePopoverRepeatImage = new Image(); blamePopoverRepeatImage = 'images/blame-popover-repeat.png';
var blamePopoverRightImage = new Image(); blamePopoverRightImage = 'images/blame-popover-right.png';

/*
 * ============================================================================
 * 
 * Window load event executes after document.ready, when the complete page is fully loaded,
 * including all frames, objects and images. For this reason caching of image and div sizes
 * should be done here.
 *  
 * ============================================================================
 */ 
$(window).load(function(){
  
  //Setup the slider
	
	$('#coda-slider-1').codaSlider({
		autoHeight: false,
		crossLinking:true,
		firstPanelToLoad:1,
		dynamicTabs: false, 
		dynamicArrows: false,
		selectionWillChangeCallback:featureSelectionWillChange,
		selectionDidChangeCallback:null,
		slideEaseDuration: 500
	});
});

/*
 * ============================================================================
 * 
 * The document ready event executes when the HTML-Document is loaded and the DOM is ready
 *  
 * ============================================================================
 */
$(document).ready(function(){

	if($.browser.msie == true && $.browser.version < 8)
		$('.toggle').addClass('display-none');

	//Setup the feature menu elements

	setupMenu();
	
	//Setup the download/buy file popovers
	
	setupFilePopovers();
	
	//Setup the promotions banner
	
	setupPromotionsBanner();
	
	//Setup the individual features
	
	setupDiff();
	setupAnnotations();
		
});

/*
 * ============================================================================
 * 
 * Setup the screenshots
 *  
 * ============================================================================
 */
function showScreenshots(id, offset) {

	if(offset == null)
		offset = 0;

	var index = screenshotGroups[id] + offset;
	
	function formatTitle(title, currentArray, currentIndex, currentOpts) {
		
		var description = currentArray[currentIndex].description;
		return '<div id="screenshots">' + '<h3>' + '<b>' + title + '</b>' + '</h3>' + '<p class="image-count">' + 'Screenshot ' + (currentIndex + 1) + ' of ' + currentArray.length + '</p>' + '<p style="clear:left;">' + description + '</p>' + '</div>';
	}
	
	$.fancybox(
		screenshots, 
		{
			'changeFade' : 0,
			'index' : index,
			'overlayColor' : 'black',
			'overlayOpacity' : 0.45,
			'padding' : 0,
			'showCloseButton' : 'true',
			'titleFormat' : formatTitle,
			'titlePosition' : 'inside',
      'transitionIn' : 'none',
      'transitionOut' : 'none',
      'type' : 'image'
		});
}

/*
 * ============================================================================
 * 
 * Menu setup
 *  
 * ============================================================================
 */
function menuFeatureAtIndex(index) {

	return $('#menu #list' + ' li:eq(' + index + ')' + ' span' + ', ' + '#mini-menu' + ' li:eq(' + index + ')' + ' span' + ' ,');
}

// ============================================================================

function featureSelectionWillChange(fromIndex, toIndex) {
	
	selectMenuFeature(toIndex - 1);
}

// ============================================================================

function selectMenuFeature(index) {

	//Update the selection index

	if(selectedMenuFeatureIndex == index)
		return;
								
	if(selectedMenuFeatureIndex != null)
		menuFeatureAtIndex(selectedMenuFeatureIndex).css('opacity', 0);
	
	var feature = menuFeatureAtIndex(index);
	feature.css('opacity', 1);
		
	selectedMenuFeatureIndex = index;
	
	//Position the indicator arrow
	
	var arrow = $('#menu #arrow');
	arrow.stop(false, true);
	
	if(index == 0 || index == 5)
	{
		//dark
		
		arrow.removeClass('arrow-light');
		arrow.removeClass('arrow-medium');	
		arrow.addClass('arrow-dark');
	}
	else if(index == 2 || index == 3)
	{		
		//light
	
		arrow.removeClass('arrow-dark');
		arrow.removeClass('arrow-medium');	
		arrow.addClass('arrow-light');
	}
	else
	{
		//medium
			
		arrow.removeClass('arrow-light');
		arrow.removeClass('arrow-dark');	
		arrow.addClass('arrow-medium');
	}
	
	arrow.animate({'opacity':0}, 80, function(){

		var offset = arrow.offset();

		offset.left = feature.offset().left + feature.width() / 2 - arrow.width() / 2;
		arrow.offset(offset);	
		
		arrow.animate({'opacity':1}, 80);
	});
}

// ============================================================================

function setupMenu() {
	
	//Main menu hover handling
	
	$("#menu #list li").hover(function (){		
	
		$(this).find('span').stop(false, true).animate({opacity: 1}, 'fast');
	},

	function(){
		
		var ele = $(this);
		
		if(ele.index() == selectedMenuFeatureIndex)
			return;
			
		ele.find('span').stop().animate({opacity: 0}, 'fast');
	});
}

/*
 * ============================================================================
 * 
 * Download/Buy Popover handling
 *  
 * ============================================================================
 */
function setupFilePopovers() {

	var targets = {'download-dummy':{'ref':'download', 'popover':'download-popover'}, 'buy-dummy':{'ref':'buy', 'popover':'buy-popover'}};
									
	//Hover handlers for each popover target

	for(var target in targets)
	{			
		$('#' + target).hover(function(){
					
			var id = $(this).attr('id');
			var obj = targets[id];
			
			var popover = $('#' + obj.popover);
			
			var settings = {'target':$(this), 'position':'middle', 'side':'top', 'endOffset':-10, 'duration':150};
			popover.showPopover(settings);
			
			var ref = $('#' + obj.ref);
			ref.addClass('button-hover');
		},

		function(){

			var id = $(this).attr('id');
			var obj = targets[id];
								
			var popover = $('#' + obj.popover);
			popover.hidePopover({'side':'top'});
			
			var ref = $('#' + obj.ref);
			ref.removeClass('button-hover');

		});
		
		//Mouse up/down handlers
		
		$('#' + target).mousedown(function(){
		
			var id = $(this).attr('id');
			var obj = targets[id];
			
			var ref = $('#' + obj.ref);
			ref.addClass('button-active');
			ref.removeClass('button-hover');
			
		});
		
		$('#' + target).bind('mouseup mouseleave', function(){
		
			var id = $(this).attr('id');
			var obj = targets[id];
								
			var popover = $('#' + obj.popover);
			popover.hidePopover({'side':'top'});
			
			var ref = $('#' + obj.ref);
			ref.removeClass('button-active');
		});
	}	
}

/*
 * ============================================================================
 * 
 * Promotions banner setup
 *  
 * ============================================================================
 */

function setupPromotionsBanner() {

	var locations = ['http://beanstalkapp.com/partners','http://codesion.com/partners.html'];
	var positions = ['-830px 0px','-590px 0px'];
	var hoverPositions = ['-830px -114px','-590px -114px']

	var timer = setInterval(showPromotion, 10000);
	var div = $('#cloud-services');
	var i = 0;
	
	function showPromotion(){
	
		i == 1? i = 0 : i++;
	
		var pos = positions[i];

		div.animate({'opacity':0}, 150, function(){

			div.css({backgroundPosition: pos});
			div.animate({'opacity':1}, 150);

			});
	}
	
	div.mouseenter(function(){
	
		var pos = hoverPositions[i];
		div.css({backgroundPosition: pos});
	})
	
	div.mouseleave(function(){
	
		var pos = positions[i];
		div.css({backgroundPosition: pos});
	})
	
	div.click(function(){
		
		var location = locations[i];			
		window.location = location;
	
	});
}

/*
 * ============================================================================
 * 
 * Setup the hover support for an array of callouts
 *  
 * ============================================================================
 */
 
function setupCalloutHoverSupport(callouts)
{
	callouts.each(function(){
	
		var callout = $(this);
		var dummy = callout.siblings(".poi-callout-dummy");
		var popover = callout.siblings(".poi-ui-popover");
		var arrow = popover.children(".poi-arrow");
		
		setupPoi(callout, dummy, popover, arrow);
		
		});
}

/*
 * ============================================================================
 * 
 * Diff setup
 *  
 * ============================================================================
 */
 
function setupDiff() {

	//Setup visibility context of the poi's
	
	var callouts = $('#features-diff #diff-screenshot .poi-callout');
	var obj = $('#features-diff #diff-screenshot');
	
	setupPoiVisibility(obj, callouts);
	
	//Setup mouse hover support for the poi's
	
	setupCalloutHoverSupport(callouts);
	
	//setup the diff edit section

	setupDiffEdit();
}

/*
 * ============================================================================
 * 
 * Diff-edit setup
 *  
 * ============================================================================
 */
function setupDiffEdit() {	
 	
 	var callouts = $('#features-diff #diff-edit-container .poi-callout');
	var obj = $('#features-diff #diff-edit-container');
	
	//setup the diff edit's poi
	
	setupPoiVisibility(obj, callouts);
	
	//setup the hover support for the poi's callout	
	
	setupCalloutHoverSupport(callouts);
 	
 	$('#diff-edit-container').click(function(){
 		
 		var on = $('#diff-edit-container #diff-edit-on');		
 		var off = $('#diff-edit-container #diff-edit-off');
	
		var duration = 50;
		
		on.stop(false, true);
		off.stop(false, true);
 		
 		if(on.css('opacity') == 1)
 		{
 			on.animate({'opacity': 0}, duration);
 			off.animate({'opacity': 1}, duration);
 		}
 		else
 		{
 		 	on.animate({'opacity': 1}, duration);
 			off.animate({'opacity': 0}, duration);
 		}
 	});
}

/*
 * ============================================================================
 * 
 * Annotations setup
 *  
 * ============================================================================
 */
function setupAnnotations() {

	//Setup poi visibility
	
	var callouts = $('#features-annotations .poi-callout');
	var obj = $('#features-annotations #blame-legend');
	
	setupPoiVisibility(obj, callouts);

	//Setup poi's
		
	var targets = {
		'#features-annotations #summary-callout':'#poi-blame-legend #summary-popover',
		'#features-annotations #timeline-callout':'#poi-blame-legend #timeline-popover',
		'#features-annotations #legend-callout':'#poi-blame-legend #legend-popover'
		};

	for(var target in targets)
	{	
		var callout = $(target);
		var dummy = callout.siblings('.poi-callout-dummy');
		var popover = $(targets[target]);
		var arrow = popover.children(".poi-arrow");
	
		setupPoi(callout, dummy, popover, arrow);
	}	
	
	//Setup blame simulation

	var gutters = {
		'#features-annotations .gutter-a':{'title':'33,408\u00a0\u00b7\u00a0steve\u00a0\u00b7\u00a0\u00a0May\u00a014,\u00a02008\u00a012:30:05\u00a0AM\u00a0\u00b7\u00a02\u00a0years\u00a0ago',
			'text': "Factored most of SourceView out into SourceFrame so it can be shared by the new ScriptView. Added the ScriptView class to be used for scripts that aren't resources."},
	
		'#features-annotations .gutter-b':{'title':'33,408\u00a0\u00b7\u00a0charlie\u00a0\u00b7\u00a0\u00a0Feb\u00a025,\u00a02010\u00a06:55:45\u00a0PM\u00a0\u00b7\u00a06\u00a0months\u00a0ago',
			'text':'2010-02-25 Charles Becks &lt;c.becks@webkit.org&gt;<br/>Reviewed by Lawrence Graham.<br/>Web Inspector: make script lines count calculation lazy.'},
			
		'#features-annotations .gutter-c' : {'title':'66,730\u00a0\u00b7\u00a0jeremy\u00a0\u00b7\u00a0\u00a0Sept\u00a03,\u00a02010\u00a04:01:33\u00a0PM\u00a0\u00b7\u00a04\u00a0days\u00a0ago',
			'text':'2010-09-03 Jeremy Wills &lt;j.wills@chromium.org&gt;<br/>Reviewed by Simon Wilson.<br/>Web Inspector: provide more information to front-end when breaking DOM event.'}
	};
	
	var popover = $("#blame-popover");
	var titleText = $("#blame-popover #title p");
	var logText = $("#blame-popover #log p");
	
	for(var gutter in gutters){
	
		$(gutter).hover(function() 
		{				
			var gutter = $(this);
			var color = gutter.css('background-color');
			var text = gutter.children('#features-annotations .text');
			var paragraph = gutter.find('p');
			
			text.stop().animate({ backgroundColor: color}, '50');
			text.css('border-width', 1);
			
			//Compensate for the border by reducing the margin by 1px
			
			text.addClass('features-annotations-comp');
			paragraph.addClass('features-annotations-comp-p');

			//Initialize the state of the popover, ensuring
			//it's starting position does not overlap the gutter,
			//since this will immediately fire a mouseleave for the
			//current gutter

			popover.css('display', 'block');
			
			var blameText = gutters['#features-annotations .' + gutter.attr('class')];
			
			titleText.text(blameText.title);
			logText.html(blameText.text);
			
			var width = titleText.width();
			popover.width(width);
			
			var settings = {
				'target':text,
				'position':'middle',
				'side':'bottom',
				'startOffset':8,
				'endOffset':8,
				'duration':100};
				
			popover.showPopover(settings);
		},
		
		function() {
		
			var gutter = $(this);
			var text = gutter.children('#features-annotations .text');
			var paragraph = gutter.find('p');

			//Hide the overlay

			text.stop().animate({ backgroundColor: 'transparent' }, 'fast');
			
			text.css('border-width', '0px');
			text.removeClass('features-annotations-comp');
			paragraph.removeClass('features-annotations-comp-p');

			//Hide the popover

			popover.hidePopover({'side':'bottom','startOffset':0, 'duration':0});
			
		});
	}
}

/*
 * ============================================================================
 * 
 * POI setup
 *  
 * ============================================================================
 */
function setupPoiVisibility(obj, callouts) {

	callouts.css('display', 'none');
	
	obj.hover(function(){
		
		callouts.stop(false, true);
		callouts.css({'opacity':0, 'display':'block'});
		callouts.animate({'opacity':1}, 250);
		
		startPoiCalloutsAnimation(callouts, 50, 2000);	
	},
	
	function()
	{					
		callouts.stop(false, true);
		callouts.data('poi-cache-active', false);
		callouts.css({'opacity':0, 'display':'none'});

	});
}

// ============================================================================

function setupPoi(callout, dummy, popover, arrow) {

	dummy.hover(function(){
	
		var settings = {'target':callout, 'position':'middle', 'cornerOffset':23, 'duration':100};

		if(arrow.hasClass('poi-left-arrow'))
			settings.position = 'left';	
		else if(arrow.hasClass('poi-right-arrow'))
			settings.position = 'right';

		popover.showPopover(settings);
		
		var id = callout.data('poi-cache-timerId');
		
		if(id != null)
			clearInterval(id);
	},
	
	function(){

		popover.hidePopover();
	});
}

// ============================================================================

function startPoiCalloutAnimation(callout) {

	//POI animation support, cycles the poi callout animation by hiding the callout's static
 	//background image and then scaling the higher resolution child image.
 	//This results in a more pleasant background effect since the higher 
 	//resolution image is not down-scaled and the lower resolution static image
 	//is not up-scaled.

	var active = callout.data('poi-cache-active');
	
	if(active == false)
		return;

	//Temporarily cache the background image being used
	
	var bkg = callout.css('background-image');
	callout.css('background-image', 'none');
	
	//Force the child image to become visible
	
	var img = callout.children('img');
	img.css('display', 'block');
	
	//'Blip' the callout, ensuring that the start opacity is still 0
	//since we want to control the visibility of the div directly
	
	callout.blip({'startOpacity':0, 'returnDuration':50}, function(){
	
		callout.css('background-image', bkg);
		img.css('display', 'none');
		callout.animate({'opacity':1}, 150);
	
	});
}

// ============================================================================

function startPoiCalloutAnimationCycle(callout, interval) {
		
	var id = setInterval(function(){
	
		startPoiCalloutAnimation(callout);
				
	}, interval)
		
	callout.data('poi-cache-timerId', id);
}

// ============================================================================

function startPoiCalloutsAnimation(callouts, gap, interval) {

	callouts.each(function(i, o){
	
			var x = $(o);
	});
	
	callouts = callouts.sort(function(a, b){
	
		var x = $(a);
		var y = $(b);
		
		return x.offset().left - y.offset().left;	
	});
	
	var wait = 0;
	
	callouts.each(function(i, o){
	
		var obj = $(o);
		
		obj.data('poi-cache-active', true);
		
		//Start an animation sequence for each item immediately
		
		setTimeout(function(){ startPoiCalloutAnimation(obj) }, wait);

		wait += gap;
	});
}

// ============================================================================

function stopPoiCalloutsAnimation(callouts) {

	callouts.each(function(i, o){
	
		var obj = $(o);
		
		var id = obj.data('poi-cache-timerId');
		
		if(id != null)
		{
			clearInterval(id);
			obj.removeData('poi-cache-timerId');
		}
	});
}

// ============================================================================

