//
// Index of the skin

var previous_section = null;

//
// Current chapter that is being edited
var current_chapter = null;
var previous_chapter_reference = null;

//
// Duration and time of the movie
var durationMovie = 0;
var timeMovie = -1;
var previousTimeMovie = 0;

var stylist_mode = edit_mode;

// indicates if we are playing
var playing = false;

//
// Duration of chapters
//var durations = new Array();

var durations_shifts = new Array(); // shifts of durations
var total_duration;

//
// Scale of the time (1s = 10 px)
var time_scale = 5;

//
// Shift of the horizontal scrollbar and time shift;
var scroll_shift = 0;
var time_shift = 0;
var totalTimeElapsed = 0;

//
// Skin configuration
var skins = 
[
[	
/* Movie location */ [32,64], 
/* Bullets location */ [383,78],
/* Chapters location */ [30,70],
/* Name location */ [20,10],
/* Reverse location */ [226,358],
/* Play location */ [263,358],
/* Pause location */ [315,358],
/* Forward location */ [368,358],
/* Check Location */ 0
],
/* 1 */ [ [20, 103], [150, 150], [410,100], [30, 395], [226, 22], [263, 22], [315, 22], [368, 22] ],
/* 2 */ [ [95, 46], [150, 150], [440,50], [150, 10], [33, 225], [28, 112], [28, 169], [33, 66] ],
/* 3 */ [ [200, 46], [150, 150], [40,50], [150, 10], [553, 226], [549, 112], [549, 169], [553, 66] ],
/* 4 */ [ [154, 58], [150, 150], [4000, 5000], [150, 10], [214, 317], [260, 312], [317, 312], [373, 317] ],
/* 5 */ [ [147, 68], [150, 150], [4000, 5000], [110, 30], [203, 347], [261, 333], [317, 333], [371, 347] ],
/* 6 */ [ [281,60], [150,150], [30,70], [20,10], [226,358], [263,358], [315,358], [368,358]],
/* 7 */ [ [160, 68], [150, 150], [4000, 5000], [110, 30], [133, 347], [223, 347], [312, 347], [403, 347] ],
/* 8 */ [ [156, 56], [150, 150], [4000, 5000], [150, 27], [203, 351], [258, 350], [329, 350], [398, 352] ],
/* 9 */ [ [274, 40], [42, 43], [4000, 5000], [40, 18], [198, 360], [261, 360], [320, 360], [373, 360], -1 ],
/* 10 */ [ [32, 54], [398, 52], [4000, 5000], [30, 18], [185, 351], [261, 351], [338, 351], [405, 351], -1 ],
/* 11 */ [ [39, 75], [383,78], [4000, 5000], [30, 18], [199, 363], [260, 350], [315, 350], [372, 363], 0 ],
/* 12 */ [ [280, 61], [25, 56], [4000, 5000], [30, 18], [209, 349], [258, 344], [318, 344], [375, 349], 2 ],
/* 13 */ [ [40, 55], [395, 54], [4000, 5000], [30, 2], [266, 364], [288, 349], [304, 403], [342, 364], 3 ],
/* 14 */ [ [38, 74], [394, 73], [4000, 5000], [30, 10], [175, 374], [258, 374], [327, 374], [387, 374], -1 ],
/* 15 */ [ [270, 64], [47, 68], [4000, 5000], [30, 1], [164, 350], [234, 350], [330, 350], [402, 350], 4 ],
/* 16 */ [ [273, 60], [35, 67], [4000, 5000], [30, 10], [168, 358], [272, 358], [318, 358], [414, 358], 5 ],
/* 17 */ [ [267, 59], [35, 60], [4000, 5000], [30, 10], [269, 324], [298, 324], [298, 370], [332, 324], 1 ],
/* 18 */ [ [43, 57], [394, 57], [4000, 5000], [30, 10], [165, 365], [298, 344], [298, 386], [413, 365], 1 ]
];

//
// Config array indices
var index_skin_movie = 0;
var index_skin_bullets = 1;
var index_skin_chapters = 2;
var index_skin_name = 3;
var index_skin_fastreverse = 4;
var index_skin_play = 5;
var index_skin_pause = 6;
var index_skin_fastforward = 7;
var index_check_location = 8;
	
var index_start = 0;
var index_end = 1;
var index_effect_in = 2;
var index_effect_in_duration = 3;
var index_effect_out = 4;
var index_effect_out_duration = 5;
var index_position_x = 6;
var index_position_y = 7;
var index_text = 8;
var index_removed = 9;
var index_chapter = 10;
var index_font = 11;
var index_style = 12;
var index_size = 13;
var index_color = 14;
var index_stack = 15;

var index_chapter_font = 0;
var index_chapter_style = 1;
var index_chapter_size = 2;
var index_chapter_default_color = 3;
var index_chapter_active_color = 4;



function $a(id)
{
	return document.getElementById(id);
}

// Shows given section
function show_section(sender)
{
	if (previous_section != null)
	{
		previous_section.style.display = "none";
	}
	previous_section = sender;
	sender.style.display = "block";
}

//
// Redraws the chapters
function redraw_chapters()
{
	//var div = $a('div_chapters_list');
	var skin = skins[current_skin_index];
	
	//div.style.left = skin[0][0] + "px";
	//div.style.top  = skin[0][1] + "px";
	
	//
	// Set the movie location
	//$a('div_flash').style.left = skin[index_skin_movie][0] + "px";
	$a('div_flash').style.left = 43 + "px";
	//$a('div_flash').style.top  = skin[index_skin_movie][1] + "px";
	$a('div_flash').style.top  = 79 + "px";
	$a('div_flash').style.display = "block";
	
	if (mode == 'stylist')
	{
	//$a('div_flash_top').style.left = skin[index_skin_movie][0] + "px";
	//$a('div_flash_top').style.top  = skin[index_skin_movie][1] + "px";
	}
	
	
	
	$a('div_chapters_list').style.display = "block";
	//$a('div_chapters_list').style.left = skin[index_skin_chapters][0] + "px";
	//$a('div_chapters_list').style.top = skin[index_skin_chapters][1] + "px";
	
	div = $a('div_username');
	//div.style.left = skin[index_skin_name][0] + "px";
	//div.style.top  = skin[index_skin_name][1] + "px";
	div.style.left = "32px";
	div.style.top  = "20px";
	div.style.display = "block";

/*
	$a('img_fastreverse').style.left = skin[index_skin_fastreverse][0] + "px";
	$a('img_fastreverse').style.top = skin[index_skin_fastreverse][1] + "px";
	$a('img_play').style.left = skin[index_skin_play][0] + "px";
	$a('img_play').style.top = skin[index_skin_play][1] + "px";
	$a('img_pause').style.left = skin[index_skin_pause][0] + "px";
	$a('img_pause').style.top = skin[index_skin_pause][1] + "px";
	$a('img_fastforward').style.left = skin[index_skin_fastforward][0] + "px";
	$a('img_fastforward').style.top = skin[index_skin_fastforward][1] + "px";
        */
}

//
// Occurs when the text in the textarea has changed
function onchapter_change(sender, div)
{
	div.innerHTML = sender.value;
}

/*

			    apply_skin();
			    current_skin_path = element.src.substring(0,element.src.lastIndexOf("/")) + "/";
				$a('cell_cart').style.backgroundImage = "url(" + element.src.substring(0,element.src.lastIndexOf("/")) + "/" + $a('select_skin_color').value + ".jpg"  + ")";
				redraw_chapters();
*/

//
// Selects the skin
var previous_skin = null;
var temp_skin_index = 0;
var current_skin_path = '';

function select_skin(sender, skin, index, initial)
{
	//
	// Get current skin bullets location
	var old_bullets_x = skins[current_skin_index][index_skin_bullets][0];
	var old_bullets_y = skins[current_skin_index][index_skin_bullets][1];
	
	temp_skin_index = index;
	current_skin_index = index;
	
	//
	// Get new skin bullets location
	var new_bullets_x = skins[current_skin_index][index_skin_bullets][0];
	var new_bullets_y = skins[current_skin_index][index_skin_bullets][1];
	
	if (mode == 'stylist')
	{
		$a('div_gridline').style.left = new_bullets_x + "px";
		$a('div_gridline').style.top = new_bullets_y + "px";
	}
	
	//$a('div_chapters_list').style.left = new_bullets_x + "px";
	//$a('div_chapters_list').style.top = new_bullets_y + "px";
	
	//new_bullets_y += $a('div_chapters_list').offsetHeight;
	//old_bullets_y += $a('div_chapters_list').offsetHeight;
	
	//
	// move all bullets with respect to top-left anchor
	for (var i=0; i < bullets.length; i++)
	{
		bullets[i][index_position_x] = bullets[i][index_position_x] - old_bullets_x + new_bullets_x;
		bullets[i][index_position_y] = bullets[i][index_position_y] - old_bullets_y + new_bullets_y;
		
		if (!isNaN(bullets[i][index_position_x]))
			$a('div_bullet_' + i).style.left = bullets[i][index_position_x] + "px";
		if (!isNaN(bullets[i][index_position_y]))
			$a('div_bullet_' + i).style.top = bullets[i][index_position_y] + "px";

	}	
	
	//current_skin_path = $a('img_skin_' + current_skin_index).src.substring(0,$a('img_skin_' + current_skin_index).src.lastIndexOf("/")) + "/";
	////$a('cell_cart').style.backgroundImage = "url(images/modules/videoresume/skins/" + skin + "/background.png)";


	if (mode != 'preview')
	{
	/*
		$a('img_fastreverse').src = "images/modules/videoresume/skins/" + skin + "/buttons/darkgray_fastreverse.png";
		$a('img_pause').src = "images/modules/videoresume/skins/" + skin + "/buttons/darkgray_pause.png";
		$a('img_play').src = "images/modules/videoresume/skins/" + skin + "/buttons/darkgray_play.png";
		$a('img_fastforward').src = "images/modules/videoresume/skins/" + skin + "/buttons/darkgray_fastforward.png";
		
		//
		// Add hovers to images
		add_hover('img_play', 'skins/' + skin + '/buttons/darkgray_play', 'png', true);
		add_hover('img_pause', 'skins/' + skin + '/buttons/darkgray_pause', 'png', true);
		add_hover('img_fastreverse', 'skins/' + skin + '/buttons/darkgray_fastreverse', 'png', true);
		add_hover('img_fastforward', 'skins/' + skin + '/buttons/darkgray_fastforward', 'png', true);
                */
	}

	redraw_chapters();
	previous_skin = sender;
	
	$a('div_skin_checkmark').style.left = (65 * ((skins[index][index_check_location]) % 2)) + "px";
	$a('div_skin_checkmark').style.top = (43 * Math.floor((skins[index][index_check_location]) / 2)) + "px";
	
	
	//
	// set the location
	
	
	check_changes();
}

var color_sender = null;
		
function change_skin_color(color, sender)
{
	
	if (color_sender != null)
		color_sender.style.borderColor = "black";

	color_sender = sender;
	
	if (current_color == "")
		current_color = "darkgray";
		
	if (current_skin_path == "")
		current_skin_path = $a('img_skin_' + current_skin_index).src.substring(0,$a('img_skin_' + current_skin_index).src.lastIndexOf("/")) + "/";
	current_color = color;
	skin_id = color;
	////$a('cell_cart').style.backgroundImage = "url(" + current_skin_path + skin_id + ".jpg"  + ")";
	check_changes();
}
var previous_color_sender = null;
function hover_color(sender)
{
	sender.style.borderColor = "red";
}

function hover_out_color(sender)
{
	if (sender == color_sender && color_sender != null)
	{
		sender.style.borderColor = "yellow";
	}
	else
		sender.style.borderColor = "black";
}

//
// Sets the duration of the movie	
function setDuration(duration, index)
{
	if (duration == undefined) return;
	durationMovie = duration;	
	if (mode == 'stylist')
	{
//slider.minimum = 0;
//slider.maximum = duration;
		
//slider.setValue((durations_shifts[current_chapter]) * time_scale / 600);
//slider.setValue(0);
}
	

}

//
// Sets the time scale
var time_scaling = false;
function setTimeScale(scale)
{
	time_scaling = true;
	// previous value of the slider
	//alert(slider.value);
	var previousValue = slider.slider('value');
	
	/*
	var v = slider.value;
	var previousValue = v;
	var previousTime = (v * 600)/ time_scale + time_shift;
	*/
	
	
	// Rescale
	if (!isNaN(total_duration) && total_duration != 0)
		time_scale = (600 / total_duration * 10 -  600 / total_duration) * scale + 600 / total_duration;
	else
		time_scale = 5;
	draw_timeline();
	rescaleTime();
	
	
	var d = scroller_horizontal.getDimensions(); onScrollHorizontal(d.x, d.y);
	
	
	
	
	//
	// Adjust scrollbar position so that scrubber is at the same position
	var difference = totalTimeElapsed - time_shift;
	var newValue = difference * time_scale / 600;
	
	var total_width = $a('table_chapter_timeline_outer').offsetWidth;

	var previousTime = Math.floor(previousValue * 600) / time_scale + time_shift;
	var newTime = Math.floor(newValue * 600) / time_scale + time_shift;
	
	var scroll_by = ( (newTime - previousTime) * total_width / total_duration );
	
	//$a('div_buffering').innerHTML = previousValue + " " + newValue + " " + scroll_by + " " + total_width;
	
	var d = scroller_horizontal.getDimensions(); 
	if (isNaN(d.x)) d.x = 0;
	//if (d.x + scroll_by < total_width)
	scrollbar_horizontal.scrollTo(d.x + scroll_by);
		
	
	generate_bullets();
	time_scaling = false;
}

//
// Rescales the timeline
function rescaleTime()
{
	//
	// Show blue borders in each chapter
	var left = 0;
	for (var i=0; i < chapter_count; i++)
	{
		var stack_max = get_stack_count(i);
		for (var j=0; j <= stack_max; j++)
		{
			if (j > 0)
				left -= durations[i] * time_scale ;//+ 4;
			
			if ($a('cell_chapter_'  + i + '_gray_' + j))
			{
				$a('cell_chapter_'  + i + '_gray_' + j).style.width = left + "px";
				$a('cell_chapter_' + i + '_blue_' + j).style.width = durations[i] * time_scale + "px";
			
				left += durations[i] * time_scale ;//+ 4;
				$a('table_chapter_timeline_' + i + "_" + j).style.width = left + "px";
			}
		}
		
	}
	
	
	
	//	alert($a('ScrollerVertical').offsetHeight);
	$a('ScrollerHorizontal').style.width = left  + "px";
	//alert($a('ScrollerHorizontal').totalWidth);
	/*
	scroller_horizontal = new Scrolling.Scroller(document.getElementById("ScrollerHorizontal"), 600, 13, null, "Horizontal");
	scrollbar_horizontal = new Scrolling.Scrollbar(document.getElementById("ScrollbarHorizontal-Container"), scroller_horizontal , new Scrolling.ScrollTween("Horizontal"), "Horizontal");
	scroller_vertical = new Scrolling.Scroller(document.getElementById("ScrollerVertical"), 13, 90, null, "Vertical");
	scrollbar_vertical = new Scrolling.Scrollbar(document.getElementById("ScrollbarVertical-Container"), scroller_vertical, new Scrolling.ScrollTween("Vertical"), "Vertical");
	*/
	scrollbar_vertical.update();
	scrollbar_horizontal.update();
}

// Sets the duration of all chapters
var durations_counter = 0;
function setDurations(index, duration)
{

	durations[index] = duration;
	
	//
	// Calculate how many chapters we got
	durations_counter++;
	var left = 0;
	if (durations_counter == chapter_count)
	{
		afterSetDurations();
	}
	if (bullets.length == 0)
		draw_timeline();
}

function afterSetDurations()
{
	total_duration = 0;
	for (var i=0; i < durations_counter; i++)
	{
		total_duration += durations[i];
		if (i == 0)
			durations_shifts[i] = 0;
		else
			durations_shifts[i] = durations_shifts[i-1] + durations[i-1];
	}
			
	if (!isNaN(total_duration) && total_duration != 0)
		time_scale = 600 / total_duration;
	else
		time_scale = 5;

	if (bullets.length == 0)
		rescaleTime();

	save();
}

function getPreviousChapterDurationsTotal()
{
	return durations_shifts[current_chapter];
}

// duration in SECONDS
function animateIn(div, effect, duration)
{
	if (isNaN(duration))
		duration = 1;
	
	duration = duration * 1000;
	if (effect == "Appear")
	{
		$(div).fadeIn(duration);
	}
	else 
	{
		if (effect == "SlideDown")
			$(div).slideDown(duration);
		else
			$(div).fadeIn(duration);
	}
}

// duration in SECONDS
function animateOut(div, effect, duration)
{
	duration = duration * 1000;
	if (effect == "Fade")
		$(div).fadeOut(duration);
	else if (effect == "SlideUp")
		$(div).slideUp(duration);
	else
		$(div).fadeOut(duration);
}
//
// Sets the current time of the movie	
function setTime(time)
{
	show_hide_all_bullets(null);
	
	//alert($a('div_username'));
	//$a('div_username').innerHTML = time;
	//alert (timeMovie + ' - ' + durationMovie);
	//var durationMovie = durations[current_chapter];
	if (durationMovie <= 0)
	{
		setDuration(durations[current_chapter]);
	}
	
	//if (!sliding)
	{
		
		previousTimeMovie = timeMovie;
		totalTimeElapsed = getPreviousChapterDurationsTotal() + timeMovie;
		sliding_by_time  = true;
		timeMovie = time;	
		if (mode == 'stylist' && !sliding)
		{
			//slider.setValue(timeMovie / durationMovie);
			var slider_value = (durations_shifts[current_chapter] + timeMovie - time_shift) * time_scale / 600;
			//$a('div_buffering').innerHTML = slider_value;
			
			// scroll if slider goes out of the screen

			if (slider_value >=0 && slider_value <= 1) $a('movie_track').style.visibility = "visible";


			if (slider_value > 1 || slider_value < 0)
			{
				var z = (slider_value > 1) ? 1 : 0;
				var currentTime = (slider_value * 600)/ time_scale + time_shift;
				var sliderTime = (z * 600) / time_scale + time_shift;
				var differenceTime = currentTime - sliderTime;
				var total_width = $a('table_chapter_timeline_outer').offsetWidth;
				var scroll_by = (differenceTime * total_width / total_duration);
				
				//totalTimeElapsed = currentTime;
				///slider.setValue(z);
				slider.slider('value', z);
				var d = scroller_horizontal.getDimensions();
				if (z == 1) scroll_by++; else scroll_by--;
				scrollbar_horizontal.scrollTo(d.x + scroll_by);
			}
			else
			{
				if (!isNaN(slider_value))
				{
					///slider.setValue(slider_value);
					slider.slider('value', slider_value);
				}
			}
			
			
		}
		sliding_by_time  = false;
		
		//
		// Check if we need to show / hide any element


		for (var i=0; i < bullets.length && playing; i++)
		{
			var bullet = bullets[i];
			var start = bullet[index_start];
			//alert(previousTimeMovie + ' - ' + start + ' - ' + timeMovie);
			$("#div_debug_michal").html("BULLET: " + i + ", PTM: " + previousTimeMovie + ", S: " + start + ", TM: " + timeMovie + ", CC: " + current_chapter + " BIC: " + bullet[index_chapter]);
			
			if (previousTimeMovie <= start && start <= timeMovie && !bullet[index_removed] && bullet[index_chapter] == current_chapter)
			{
				var div = $a('div_bullet_' + i);
				
				animateIn(div, bullet[index_effect_in], bullet[index_effect_in_duration]);
			//var s = 'new Effect.' + bullet[index_effect_in] + '(div, { duration: ' + bullet[index_effect_in_duration] + '})';
			//eval(s);
			}
			var end = bullet[index_end];
			if (previousTimeMovie <= end && end <= timeMovie && !bullet[index_removed] && bullet[index_chapter] == current_chapter)
			{
				var div = $a('div_bullet_' + i);
				animateOut(div, bullet[index_effect_out], bullet[index_effect_out_duration]);
			//var s = 'new Effect.' + bullet[index_effect_out] + '(div, { duration: ' + bullet[index_effect_out_duration] + '})';
			//eval(s);
			}
		}
	}
	
	//$a('div_username').innerHTML = time + ' ' + durationMovie + ' ' + current_chapter  + '  ' + chapter_count;// + ' - ' + sliding;
	//$a('cell_test').innerHTML = time + " " + durationMovie;
	if (time >= (durationMovie - 0.01)&& /* mode == 'preview' && */  durationMovie != 0) 
	{
		if (current_chapter < chapter_count - 1 )
		{
			//alert('selectChapter time: ' + time + ' durationMovie: ' + durationMovie );
			//if (mode != 'preview')
			select_chapter(current_chapter+1, true);
			if (mode == 'stylist') scroll_to_chapter(current_chapter);
			playCompletedManual();
		}
		/*
		if (current_chapter >= chapter_count - 1 )
		{
			// in case of last chaptger
			playCompletedManual();
		}
		*/
	}

	if (mode == 'stylist' && !sliding)
	{
		sliding_by_time  = false;	
	}

}


//
// Changes the effect on demo
function test_effect_demo()
{
	var effect = $a('select_effect_in').value;
	var duration = parseFloat($a('select_effect_in_duration').value) * 1000;
	var div = $a('demo-effect-slidedown');

	if (effect == "Appear")
		$(div).fadeIn(duration, effect_demo_in_finished);
	else if (effect == "SlideDown")
		$(div).slideDown(duration, effect_demo_in_finished);
	else
		$(div).fadeIn(duration, effect_demo_in_finished);
//var s = 'new Effect.' + effect + '(div, { duration: ' + duration + ', afterFinish: effect_demo_in_finished} )';
//eval(s);
}


function effect_demo_in_finished(obj){
	var effect = $a('select_effect_out').value;
	var duration = parseFloat($a('select_effect_out_duration').value) * 1000;
	var div = $a('demo-effect-slidedown');

	if (effect == "Fade")
		$(div).fadeOut(duration, effect_demo_out_finished);
	else if (effect == "SlideUp")
		$(div).slideUp(duration, effect_demo_out_finished);
	else
		$(div).fadeOut(duration, effect_demo_out_finished);
//eval('new Effect.' + effect + '(div, { duration: ' + duration + ', afterFinish: effect_demo_out_finished} )');
}

function effect_demo_out_finished(obj)
{
}

//
// Bullets manipulation
var bullet_selected = null;

//
// Selects the bullet
function select_bullet(bullet_index)
{
	
	//if ($a('div_add_edit_bullet').style.display == 'none')
	//	show_edit_bullet();
	if (stylist_mode  != 'edit') return;
	
	
	if (bullet_selected != null)
	{
		//$a('div_bullet_' + bullet_selected).style.display = "none";
		$a('div_bullet_' + bullet_selected).style.border = "";
		$a('div_bullet_' + bullet_selected).style.zIndex = "10";
	}
	
	bullet_selected = bullet_index;
	//$a('div_bullet_' + bullet_selected).style.display = "block";
	$a('div_bullet_' + bullet_selected).style.border = "1px red dotted";
	$a('div_bullet_' + bullet_selected).style.zIndex = "100";
	
//
// Fill the fields
/*
	var row = bullets[bullet_selected];
	//$a('input_time_start').value = row[index_start];
	$a('input_duration').value = Math.round(100 * (row[index_end] - row[index_start])) / 100;
	$a('textarea_bullet_text').value = row[index_text];
	$a('select_effect_in').value = row[index_effect_in];
	$a('select_effect_in_duration').value = row[index_effect_in_duration];
	$a('select_effect_out').value = row[index_effect_out];
	$a('select_effect_out_duration').value = row[index_effect_out_duration];
	*/
}

//
// Applies the changes made to the bullet
function update_chapter()
{
	if (chapter_selected >= 0)
	{
		// check if we have any data
		if (trim($a('input_chapter_text').value) == "")
		{
			alert("You cannot save empty chapter title");
			return;
		}

		var row = chapters[chapter_selected];
		row[index_chapter_font] = $a('select_chapter_font').value;
		row[index_chapter_style] = $a('select_chapter_style').value;
		row[index_chapter_size] = $a('select_chapter_size').value;
		row[index_chapter_default_color] = $a('input_chapter_default_color').value;
		row[index_chapter_active_color] = $a('input_chapter_active_color').value;
		
	
		$a('div_chapter_' + chapter_selected).innerHTML = trim($a('input_chapter_text').value);
		
		$('#cell_chapter_heading_' + chapter_selected).html(trim($('#input_chapter_text').val()));
		$("#input_chapter_heading_hidden_" + chapter_selected).val(trim($('#input_chapter_text').val()));

		/*
		$a('div_chapter_' + chapter_selected).style.fontFamily = row[index_chapter_font];
		$a('div_chapter_' + chapter_selected).style.fontStyle = (row[index_chapter_style].indexOf("italic") > 0) ? "italic" : "";
		$a('div_chapter_' + chapter_selected).style.fontWeight = (row[index_chapter_style].indexOf("bold") > 0) ? "bold" : "";
		$a('div_chapter_' + chapter_selected).style.fontSize = row[index_chapter_size] + "px";
		$a('div_chapter_' + chapter_selected).style.color = row[index_chapter_default_color].replace(';','');
		*/
	/*
		new Effect.Fade($a('dhtml_goodies_id2'), { duration: 0.5, afterFinish: function() 
			{ 
				
			}
		});
		*/
		
	}
	//check_chapter_width();
	
	check_changes();
	$("#div_chapters").dialog('close');
}

//
// Applies the changes made to the bullet
function update_bullet()
{
	if ( $("#input_bullet_text").attr("value") == '' )
	{
		$("#no-bullet-text-error").show();
		return false;
	}
	
	if (bullet_selected >= 0)
	{
		var row = bullets[bullet_selected];
		//row[index_start] = durations[row[index_chapter]] * slider_track_bullet_start.value;
		
		//var dur = durations[row[index_chapter]] * slider_track_bullet_duration.value
		//row[index_end] = row[index_start] + dur;
		//row[index_end] = row[index_start] + Math.round(100*parseFloat($a('input_duration').value))/100;
		row[index_text] = $a('input_bullet_text').value;
		row[index_effect_in] = $a('select_effect_in').value;
		row[index_effect_in_duration] = $a('select_effect_in_duration').value;
		row[index_effect_out] = $a('select_effect_out').value;
		row[index_effect_out_duration] = $a('select_effect_out_duration').value;
		row[index_font] = $a('select_bullet_font').value;
		row[index_style] = $a('select_bullet_style').value;
		row[index_size] = $a('select_bullet_size').value;
		row[index_color] = $a('input_bullet_color').value;
		
		/*	
		$a('input_bullet_start_' + bullet_selected).value = row[index_start];
		$a('input_bullet_end_' + bullet_selected).value = row[index_end];
		$a('input_bullet_text_' + bullet_selected).value = row[index_text];
		*/
		
		$a('div_bullet_' + bullet_selected).innerHTML = "<div>" + row[index_text] + "</div>";
		
		$a('div_bullet_' + bullet_selected).style.fontFamily = row[index_font];
		$a('div_bullet_' + bullet_selected).style.fontStyle = (row[index_style].indexOf("italic") > 0) ? "italic" : "";
		$a('div_bullet_' + bullet_selected).style.fontWeight = (row[index_style].indexOf("bold") > 0) ? "bold" : "";
		$a('div_bullet_' + bullet_selected).style.fontSize = row[index_size] + "px";
		$a('div_bullet_' + bullet_selected).style.color = row[index_color].replace(';','');
		
		/*
		new Effect.Appear($a('div_bullets_table'), { duration: 2});
		new Effect.SlideUp($a('div_add_edit_bullet'), { duration: 1});
		*/
		
		/*
		new Effect.Fade($a('dhtml_goodies_id1'), { duration: 0.5, afterFinish: function() 
			{ 
				
			}
		});
		*/
		//		$a('dhtml_goodies_id1').style.display = "none";
		//showSelectSkin();
			
		generate_bullets();

	}
	check_changes();
	show_hide_all_bullets(null);
	$('#div_bullets_setup').dialog("close");
}

function cancel_bullet()
{
	$("#div_bullets_setup").dialog('close');
}

function cancel_chapter()
{
	$("#div_chapters").dialog('close');
}
//
// Adds new bullet
var add_bullet_chapter_index;
function add_bullet()
{
	if ( $("#input_bullet_text").attr("value") == '' )
	{
		$("#no-bullet-text-error").show();
		return false;
	}
	var skin = skins[current_skin_index];

	
	//new Effect.SlideUp($a('div_add_edit_bullet'), { duration: 1});
	//new Effect.Appear($a('div_bullets_table'), { duration: 2});
	
	//
	// Add the values to array
	//var start = parseFloat($a('input_time_start').value);
	//var start = durations[add_bullet_chapter_index] * slider_track_bullet_start.value;
	var start = 0;
	//var duration = durations[add_bullet_chapter_index] * (slider_track_bullet_duration.value + 0.3);
	var duration = durations[add_bullet_chapter_index] / 2;
	var end = start + duration;
	var text = $a('input_bullet_text').value;
	var effect_in = $a('select_effect_in').value;
	var effect_in_duration = $a('select_effect_in_duration').value;
	var effect_out = $a('select_effect_out').value;
	var effect_out_duration = $a('select_effect_out_duration').value;
	var font = $a('select_bullet_font').value;
	var style = $a('select_bullet_style').value;
	var size = $a('select_bullet_size').value;
	var color = $a('input_bullet_color').value;

	
	var rowArray = new Array();
	rowArray[index_start] = start;
	rowArray[index_end] = end;
	rowArray[index_effect_in] = effect_in;
	rowArray[index_effect_in_duration] = effect_in_duration;
	rowArray[index_effect_out] = effect_out;
	rowArray[index_effect_out_duration] = effect_out_duration;
	rowArray[index_position_x] = skin[1][0];//parseInt($a('div_chapters_list').style.left);
	rowArray[index_position_y] = skin[1][1];//parseInt($a('div_chapters_list').style.top) + $a('div_chapters_list').offsetHeight + offset;
	rowArray[index_text] = text;
	rowArray[index_removed] = 0;
	rowArray[index_chapter] = add_bullet_chapter_index;
	rowArray[index_font] = font;
	rowArray[index_style] = style;
	rowArray[index_size] = size;
	rowArray[index_color] = color;
	rowArray[index_stack] = 0;
	
	//bullets.push(start, end, effect_in, effect_in_duration, effect_out, effect_out_duration, text);
	bullets.push(rowArray);
	

	
	//
	// Create div
	var index = bullets.length-1;
	var div = document.createElement("DIV");
	div.innerHTML = text;
	div.id = 'div_bullet_' + index;
	div.className = "item_bullet";
	//div.style.width = "200px";
	$a('div_bullets').appendChild(div);
	//$a('div_bullets').innerHTML = $a('div_bullets').innerHTML + '<div style="position:absolute; left:50px; top:50px; " class="item_bullet" id="div_bullet_' + index + '">' + text + '</div>';

	div.style.left = skin[1][0] + "px";
	div.style.top  = skin[1][1] + "px";
	div.style.wordWrap = "break-word";
	div.style.maxWidth = "390px";
	//div.style.left = $a('div_chapters_list').style.left;
	var offset = 0;
	for (var i=0; i < bullets.length - 1; i++)
		offset += $a('div_bullet_' + i).offsetHeight;
		
	/////div.style.top = (parseInt($a('div_chapters_list').style.top) + $a('div_chapters_list').offsetHeight + offset) + "px";
	

	div.style.fontFamily = font;
	div.style.fontStyle = (style.indexOf("italic") > 0) ? "italic" : "";
	div.style.fontWeight = (style.indexOf("bold") > 0) ? "bold" : "";
	div.style.fontSize = size + "px";
	div.style.color = color.replace(';','');


	//
	// Make it draggable
	///new Draggable('div_bullet_' + index, {change:function(d) {move_bullet(index);} });
	$("#div_bullet_" + index).draggable({
		stop: function(event,ui) {
			move_bullet(index)
		}
	});

	//TODO: Hide Add bullets
		
	generate_bullets();
	
	//
	// Select the bullet as current
	//$a('radio_bullet_' + index).checked = true;
	//select_bullet($a('radio_bullet_' + index));
	//$a('img_show_add_bullet').style.visibility = "visible";
	check_changes();
	show_hide_all_bullets(null);

	$("#div_bullets_setup").dialog('close');
}




//
// Changes to edit mode
function edit_mode()
{
	stylist_mode  = 'edit';
	
	//
	// Hide all the bullets
	for (var i=0; i < bullets.length; i++)
	{
		if (!bullets[i][index_removed] && bullets[i][index_chapter] == current_chapter)
			$a('div_bullet_' + i).style.display = 'block';
	}
	show_hide_all_bullets(null);

}

//
// Changes to preview mode
function preview_mode()
{
	stylist_mode  = 'preview';
	
	//
	// Hide all the bullets
//	for (var i=0; i < bullets.length; i++)
//	{
//		$a('div_bullet_' + i).style.display = 'none';
//	}
	if (bullet_selected != null)
	{
		//$a('div_bullet_' + bullet_selected).style.display = "none";
		$a('div_bullet_' + bullet_selected).style.border = "";
	}
}

//
// Gets the string for saving data
function get_save_data(return_object)
{
	//
	// Get the chapters
	var c = "";
	
	for (var i=0; i < chapter_count; i++)
	{
		c += trim($a('cell_chapter_heading_' + (i)).innerHTML) + '[||]';
		c += durations[i] + '[||]';
		c += chapters[i][index_chapter_font] + "[||]";
		c += chapters[i][index_chapter_style] + "[||]";
		c += chapters[i][index_chapter_size] + "[||]";
		c += chapters[i][index_chapter_default_color] + "[||]";
		c += chapters[i][index_chapter_active_color] + "[||]";
		c += "[|||]";
	}
	
	// Get bullets	
	var b = "";
	for (var i=0; i < bullets.length; i++)
	{
		if (bullets[i][index_removed]) continue;
		var row = bullets[i];
		b += row[index_start] + "[||]";
		b += row[index_end] + "[||]";
		b += row[index_effect_in] + "[||]";
		b += row[index_effect_in_duration] + "[||]";
		b += row[index_effect_out] + "[||]";
		b += row[index_effect_out_duration] + "[||]";
		b += row[index_position_x] + "[||]";
		b += row[index_position_y] + "[||]";
		b += row[index_text] + "[||]";
		b += row[index_chapter] + "[||]";
		b += row[index_font] + "[||]";
		b += row[index_style] + "[||]";
		b += row[index_size] + "[||]";
		b += row[index_color] + "[||]";
		b += "[|||]";
	}
	//b = escape(b);
	
	//
	// get name position
	var name_x = $a('div_username').style.left;
	var name_y = $a('div_username').style.top;
	var chapters_x = $a('div_chapters_list').style.left;
	var chapters_y = $a('div_chapters_list').style.top;
	
	var p = 'skin=' + skin_id + '&skin_index=' + current_skin_index +  '&chapters=' +  encodeURIComponent(c) + '&bullets=' + encodeURIComponent(b) + "&name_x=" + name_x + "&name_y=" + name_y  + "&chapters_x=" + chapters_x  + "&chapters_y=" + chapters_y;
	if (return_object == true)
		p = {
			skin: skin_id ,
			skin_index: current_skin_index ,
			chapters: c,
			bullets : b,
			name_x: name_x,
			name_y : name_y,
			chapters_x : chapters_x,
			chapters_y : chapters_y
		};
			
	return p;
}



//
// Saves the stylist
function save()
{
	var p = get_save_data(true);
	
	//alert(p);
	$('#span_information').html("Saving ...");
	$.ajax(
	{
		type: 'POST',
		url: 'modules/videoresume/stylistSave.php',
		data: p,
		error: function (XMLHttpRequest, textStatus, errorThrown)
		{
			$('#span_information').html("There was some problem!");
		},
		success: function(html)
		{
			$('#span_information').html("Saved successfully.");
		}
	});

}


//
// moves the bullet
function move_bullet(index)
{
	//var left = $a('div_bullet_' + index).offsetLeft;
	//var top = $a('div_bullet_' + index).offsetTop;
	move_bullets_constraint();
	
	var left = $a('div_bullet_' + index).style.left.replace("px","");
	var top = $a('div_bullet_' + index).style.top.replace("px","");
	
	
	//
	// Update position
	bullets[index][index_position_x] = left;
	bullets[index][index_position_y] = top;
	
	
	
	check_changes();
}

//
// Removes given bullet
function delete_bullet(index)
{
	//$a('row_bullet_' + index).style.display = "none";
	index = bullet_selected;
	if (index >= 0)
	{
		bullets[index][index_removed] = 1;
		bullets[index][index_start] = -100;
		$a('div_bullet_' + index).style.display = "none";
		generate_bullets();

	/*
		new Effect.Fade($a('dhtml_goodies_id1'), { duration: 0.5, afterFinish: function() 
		{ 
				
		}
		});
		*/

	}
	check_changes();
	$('#div_bullets_setup').dialog("close");
}

function trim(str)
{
	s = str.replace(/^(\s)*/, '');
	s = s.replace(/(\s)*$/, '');
	return s;
}
 
 
var isIE = (navigator.appName.indexOf("Microsoft") != -1);

//
// Selects given chapter 
function select_chapter(index, shouldplay)
{
	
	//alert("Select chapter: " + index + ". Should play? : " + shouldplay + ". Current chapter: " + current_chapter);
	//alert(index);
	if (current_chapter == index) return;
	if (previous_chapter_reference != null)
	{
		previous_chapter_reference.className = "chapter";
		if (chapters[current_chapter][index_chapter_default_color] != "")
			previous_chapter_reference.style.color = chapters[current_chapter][index_chapter_default_color].replace(';','');

		//
		// Check if we need to show / hide any element
		for (var i=0; i < bullets.length; i++)
		{
			var bullet = bullets[i];
			var div = $a('div_bullet_' + i);
			if (!bullet[index_removed] && bullet[index_chapter] == current_chapter && div.style.display != 'none')
			{

				//var s = 'new Effect.' + bullet[index_effect_out] + '(div, { duration: ' + bullet[index_effect_out_duration] + '})';
				//eval(s);
				div.style.display = "none";
			}
		}
	}
	
	var r = $a("div_chapter_" + index);
	r.className = "chapter_selected";
	if (chapters[index][index_chapter_active_color] != "")
		r.style.color = "#000000"; //chapters[index][index_chapter_active_color].replace(';','');
	current_chapter = index;
	
	//
	// Hide all the bullets and rows that are not in current section
	/*
	for (var i=0; i < bullets.length; i++)
	{
		
		if (bullets[i][index_chapter] == current_chapter && !bullets[i][index_removed] && mode == 'stylist')
		{
			$a('div_bullet_' + i).style.display = 'block';
			if (mode == 'stylist')
				$a('row_bullet_' + i).style.display = (isIE) ? 'block' : 'table-row';
		}
		else
		{
			$a('div_bullet_' + i).style.display = 'none';
			if (mode == 'stylist')
				$a('row_bullet_' + i).style.display = 'none';
		}
	}
	*/
	previous_chapter_reference = r;
	
	
	
	//
	// If preview mode - start playing in by setPreviewVideo
	//if (mode == 'preview')
	
	if (shouldplay)
	{
		flash.setPreviewVideo(current_chapter);
	}
	else
	{
		//
		// select content path in the flash
		flash.setVideo(current_chapter);
	}
	handleStylistButtonChange();
}	

function testStylist(test)
{
	alert('test: ' + test);
}

//
// Occurs when we reach the end of the video
function playCompleted()
{

}
function playCompletedManual()
{
	
	
	//	alert('playCompleted');
	if (mode == 'preview' )
	{
		if (current_chapter == chapter_count - 1)
			{
				playing = false;
			}

		/*
		if (current_chapter <= chapter_count - 1)
		{
			select_chapter(current_chapter+1, true);
		}
		else
		{
			playing = false;
			flash.pauseStylist();
			select_chapter(0); scroll_to_chapter(0); setTime(0);
		}
		*/
	}
	
	if (mode == 'stylist' && current_chapter == chapter_count)
	{
		playing = false;
		flash.pauseStylist();
		select_chapter(0); scroll_to_chapter(0); setTime(0);
	}
}

//
// Shows the add bullet section
function show_add_bullet(chapter_index)
{
    
	showAddBullet();
	add_bullet_chapter_index = chapter_index;
	
	//
	// Fill values
	$a('input_bullet_text').value = "";
	$a('select_bullet_size').value = 12;
	$a('input_bullet_color').value = "#ffffff";
	$a('div_bullet_color').style.backgroundColor = "#ffffff";
	
	$a('img_delete_bullet').style.display = "none";
	$a('img_update_bullet').style.display = "none";
	$a('img_save_bullet').style.display = "block";
	
	
	
}

//
// Shows the edit bullet section
function show_edit_bullet(index)
{
	
	showAddBullet();
	
	bullet_selected = index;
	// 
	// Fill the data
	var bullet = bullets[index];
	$a('input_bullet_text').value = bullet[index_text];
	
	//
	// Set start and duration
	slider_track_bullet_start.slider('value', bullet[index_start] / durations[bullet[index_chapter]]);
	slider_track_bullet_duration.slider('value', (bullet[index_end] - bullet[index_start]) / durations[bullet[index_chapter]]);
	
	$a('select_effect_in').value = bullet[index_effect_in];
	
	
	$a('select_effect_in_duration').value = (bullet[index_effect_in_duration] * 10 % 2 == 0) ? bullet[index_effect_in_duration] + ".0" : bullet[index_effect_in_duration];
	$a('select_effect_out').value = bullet[index_effect_out];
	$a('select_effect_out_duration').value = (bullet[index_effect_out_duration] * 10 % 2 == 0) ? bullet[index_effect_out_duration] + ".0" : bullet[index_effect_out_duration];

	$a('select_bullet_font').value = bullet[index_font];
	$a('select_bullet_style').value = bullet[index_style];
	
	$a('select_bullet_size').value = bullet[index_size];
	$a('input_bullet_color').value = bullet[index_color];
	$a('div_bullet_color').style.backgroundColor = bullet[index_color].replace(';', '');

	$a('img_delete_bullet').style.display = "block";
	$a('img_update_bullet').style.display = "block";
	$a('img_save_bullet').style.display = "none";
	
	
}


var chapter_selected = null;
//
// Shows the edit chapter section
function show_edit_chapter(index)
{
	chapter_selected = index;
	// 
	// Fill the data
	var chapter = chapters[index];
	
	//$('#input_chapter_text').val(trim($('#cell_chapter_heading_' + index).html()));
	$('#input_chapter_text').val($("#input_chapter_heading_hidden_" + chapter_selected).val());
	
	$a('select_chapter_font').value = chapter[index_chapter_font];
	$a('select_chapter_style').value = chapter[index_chapter_style];
	$a('select_chapter_size').value = chapter[index_chapter_size];
	$a('input_chapter_default_color').value = chapter[index_chapter_default_color];
	$a('input_chapter_active_color').value = chapter[index_chapter_active_color];

	$a('div_chapter_default_color').style.backgroundColor = chapter[index_chapter_default_color].replace(';', '');
	$a('div_chapter_active_color').style.backgroundColor = chapter[index_chapter_active_color].replace(';', '');
	
	$("#div_chapters").dialog('open');
}


/* Adds the hover functionality to the img */
var hover_images = new Array();
function add_hover(img_id, image_name, extension, clicked)
{
	hover_images[img_id] = new Array();
	hover_images[img_id][0] = new Image();
	hover_images[img_id][0].src = urlStylist + "/images/modules/videoresume/" + image_name + "." + extension;
	
	hover_images[img_id][1] = new Image();
	hover_images[img_id][1].src = urlStylist + "/images/modules/videoresume/" + image_name + "_hover." + extension;
	
	$a(img_id).onmouseover = function()
	{
		this.src = hover_images[this.id][1].src;
	}
	$a(img_id).onmouseout = function()
	{
		this.src = hover_images[this.id][0].src;
	}
	if (clicked)
	{
		hover_images[img_id][2] = new Image();
		hover_images[img_id][2].src = urlStylist + "/images/modules/videoresume/" + image_name + "_clicked." + extension;
		$a(img_id).onmousedown = function()
		{
			this.src = hover_images[this.id][2].src;
		}
		$a(img_id).onmouseup = function()
		{
			this.src = hover_images[this.id][1].src;
		}
	}
	

}

//
// Returns the maximal stack number for given chapter
function get_stack_count(chapter_index)
{
	var stack_max = 0;
	for (var i=0; i < bullets.length; i++)
	{
		if (bullets[i][index_chapter] == chapter_index && bullets[i][index_stack] > stack_max)
			stack_max = bullets[i][index_stack];
	}
	return stack_max;
}

//
// Generates bullets on the screen timeline
function generate_bullets()
{
	
	//
	// Clear bullets
	for (var i=0; i < chapter_count; i++)
	{
		var stack_max = get_stack_count(i);
		for (var j=0; j <= stack_max; j++)
		{
			var table = $a('table_timeline_bullets_' + i + '_' + j);
			while (table.rows.length > 0)
				table.deleteRow(0);
		}
	}
	
	
	for (var i=0; i < bullets.length; i++)
	{
		//
		// calculate left position and width
		//
		// Show blue borders in each chapter
		var chapter_index = bullets[i][index_chapter];
		var left = bullets[i][index_start] * time_scale - 0;
		var width = (bullets[i][index_end] - bullets[i][index_start]) * time_scale - 0;
		
		var s = '<div unselectable id="div_bullet_timeline_' + i + '" style="cursor:move;position:relative; float:left; left: ' + left + 'px; top:0px; background-color: #000099; width: ' + width + 'px; margin-top: 0px; height: 15px; color: white; border: 1px solid #0000FF; text-align:center; vertical-align:middle;" ondblclick="show_edit_bullet(' + i + ')"  onclick="select_bullet(' + i + ')">';
		s += '<div unselectable onmousedown="bullet_down($a(\'div_bullet_timeline_' + i + '\'),event, ' + chapter_index + ', \'move\', ' + i + ')" style="width:100%;text-align:center; padding-left: 2px; overflow:hidden; font-size:8px; float:left; height: 15px">' + bullets[i][index_text] + '</div>';
		s += '<div style="background-image:url(' + urlStylist + '/images/modules/videoresume/styler/bulletarrows.png); width:19px; height:9px; float:right; position:absolute; right: -9px; top:3px; cursor: e-resize;" onmousedown="bullet_down($a(\'div_bullet_timeline_' + i + '\'),event, ' + chapter_index + ', \'resize\', ' + i + ')"></div>';
		s += '</div>';

		if (bullets[i][index_chapter] >= 0 && bullets[i][index_chapter] < chapter_count && !bullets[i][index_removed])
		{
			var table = $a('table_timeline_bullets_' + bullets[i][index_chapter] + '_' + bullets[i][index_stack]);
			var row = table.insertRow(table.rows.length);
			var cell = row.insertCell(0)
			cell.innerHTML += s;
			cell.vAlign = "top";
			
			//alert(table.parentNode.parentNode.parentNode.offsetHeight);
			$a('cell_chapter_heading_' + bullets[i][index_chapter]).style.height = (table.parentNode.parentNode.parentNode.offsetHeight + 1) + "px" ;
		}
	}

	scrollbar_vertical.update();
	scrollbar_horizontal.update();
}




//
// occurs when the bullet is clicked
var slider_bullet;
var mouseover;
var sliderBulletMax = 200;
var evnt = null;
var currentMode;
var bulletWidth;
var bulletIndex;

function bullet_down(sender, evnt, chapter_index, mode, bullet_index)
{
	
	bulletIndex = bullet_index;
	currentMode = mode;
	if (!evnt) evnt = window.event; // Get the mouse event causing the slider activation.
	
	//
	// Set the max bullet slider
	sliderBulletMax = parseInt($a('cell_chapter_' + chapter_index + '_blue_' + 0).style.width) - parseInt(sender.style.width) - 4;
	slider_bullet = sender;
	slider_bullet.startOffsetX = bullet_left(slider_bullet.id) - evnt.screenX;	
	mouseover = true;
	bulletWidth = parseInt(sender.style.width);
	document.onmousemove = bullet_move // Start the action if the mouse is dragged.
	document.onmouseup = bullet_up // Stop sliding.
	return false
}

//
// moves the handler
function bullet_move(evnt)
{
	var evnt = (!evnt) ? window.event : evnt; // The mousemove event
	if (mouseover) { // Only if slider is dragged
		x = slider_bullet.startOffsetX + evnt.screenX // Horizontal mouse position relative to allowed slider positions
		//y = slider.startOffsetY + evnt.screenY // Horizontal mouse position relative to allowed slider positions
		if (x > sliderBulletMax) x = sliderBulletMax // Limit horizontal movement
		if (x < 0 && currentMode == "move") x = 0 // Limit horizontal movement
		if (x < -bulletWidth && currentMode == "resize") x = -bulletWidth // Limit horizontal movement
		bullet_left(slider_bullet.id, x)  // move slider to new horizontal position
		return false
	}
	return
}

function bullet_left(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.left) == 'string')) {
		
		if (typeof(pos) == 'number') 
		{
			if (currentMode == "move")
				elmnt.style.left = (pos) + 'px';
			else
			{
				var newWidth = (bulletWidth + (pos - parseInt(elmnt.style.left)));
				if (newWidth < 15)
					newWidth = 15;
				elmnt.style.width = newWidth + 'px';
			}
				
			bullets[bulletIndex][index_start] = (parseInt(slider_bullet.style.left) + 0) / time_scale;
			bullets[bulletIndex][index_end] = (parseInt(slider_bullet.style.width) + 0) / time_scale + bullets[bulletIndex][index_start];
			show_hide_all_bullets(null);
			check_stack_down(elmnt);
		}
		else {
			pos = parseInt(elmnt.style.left);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelLeft) {
		if (typeof(pos) == 'number') elmnt.style.pixelLeft = pos;
		else pos = elmnt.style.pixelLeft;
	}
	return pos;
}


//
// occurs when the handler is released
function bullet_up(evnt)
{
	if (mouseover) {
	

		//
		// Update bullet information
		bullets[bulletIndex][index_start] = (parseInt(slider_bullet.style.left) + 0) / time_scale;
		bullets[bulletIndex][index_end] = (parseInt(slider_bullet.style.width) + 0) / time_scale + bullets[bulletIndex][index_start];
		if (document.removeEventListener) { // Remove event listeners from 'document' (W3C).
			document.removeEventListener('mousemove', bullet_move, false)
			document.removeEventListener('mouseup', bullet_up, false)
		}
		else if (document.detachEvent) { // Remove event listeners from 'document' (IE).
			document.detachEvent('onmousemove', bullet_move)
			document.detachEvent('onmouseup', bullet_up)
		}
		mouseover = false // Stop the sliding.
		check_changes();
	}
		
}
	
	
	
//
// checks if any bullet requires stacking and stack down if necessary	
function check_stack_down(sender, index)
{
	return;
	var i = bulletIndex;
	if ($a('div_bullet_timeline_' + i) != sender)
		i = bullet_selected;
	if ($a('div_bullet_timeline_' + i) != sender)
		i = index;
	
	var chapter_index = bullets[i][index_chapter];
	
	var requires_stacking = false;
	for (var k=0; k < bullets.length; k++)
	{
		if (bullets[k][index_chapter] != bullets[i][index_chapter]) continue;
		if (k == i || bullets[i][index_stack] != bullets[k][index_stack]) continue;
			
		//$a('cell_test').innerHTML = "((" + bullets[i][index_start] + "<" +  bullets[k][index_start] + ") && (" + bullets[i][index_end] + ">" +  bullets[k][index_start] + "))";
		//
		// Check if we need to stack up given element
		if (
			((bullets[i][index_start] < bullets[k][index_start]) && (bullets[i][index_end] > bullets[k][index_start]))
			||
			((bullets[k][index_start] < bullets[i][index_start]) && (bullets[k][index_end] > bullets[i][index_start]))
			)
			{
			bullets[k][index_stack]++;
			//
			// check if we need to create new row to accomodate
			
			var table = $a('table_chapter_timeline_outer');
		
			if (table.rows.length-1 < 1);//bullets[k][index_stack])
			{
				var row_index = 1;
				var row = table.insertRow(row_index);//table.rows.length);
				var cell = row.insertCell(0);
				cell.style.backgroundImage = "url(" + urlStylist + "/images/modules/videoresume/graytile.png);";
				cell.style.height = "31px;";
				
				//
				// Insert the content of the cell
				var s = '<table cellpadding="0" cellspacing="0" id="table_chapter_timeline_' + chapter_index + '_' + bullets[k][index_stack] + '" style="position:relative;">';
				s += '<tr>';
				s += 	'<td style="width:' + $a('cell_chapter_' + chapter_index + '_gray_' + (bullets[k][index_stack]-1)).style.width + '" id="cell_chapter_' + chapter_index + '_gray_' + bullets[k][index_stack] + '"></td>';
				s +=	'<td id="cell_chapter_' + chapter_index + '_blue_' + bullets[k][index_stack] + '" style="background-image: url(' + urlStylist + '/images/modules/videoresume/bluetile.png); height: 31px; width: ' + (parseInt($a('cell_chapter_' + chapter_index + '_blue_' + (bullets[k][index_stack]-1)).style.width)-0) +'px">';
				s +=		'<div style="float: left; background-image: url(' + urlStylist + '/images/modules/videoresume/blueleftcap.png); height: 30px; width: 4px;"></div>';
				s +=		'<div id="div_timeline_bullets_' + chapter_index + '_' + bullets[k][index_stack] + '">';
				s +=		'</div>';
				s +=	'</td>';
				s +=	'<td>';
				s +=		'<div style="float: right; background-image: url(' + urlStylist + '/images/modules/videoresume/bluerightcap.png); height: 30px; width: 4px;"/></div>';
				s +=    '</td>';
				s +=   '</tr>';
				s +=  '</table>';
				    
				cell.innerHTML = s;
				 
				row = $a('table_chapters').insertRow(row_index);
				cell = row.insertCell(0);
				cell.colSpan = 2;
				cell.style.height = "30px"
				cell.style.backgroundImage = "url(" + urlStylist + "/images/modules/videoresume/styler/chaptertile.png)";
				cell.innerHTML = "-";
			}
			//
			// Append child
			$a('div_timeline_bullets_' + chapter_index + '_' + bullets[k][index_stack]).appendChild($a('div_bullet_timeline_' + k));
			check_stack_down($a('div_bullet_timeline_' + k), k);
			
			
			requires_stacking = true;
		}
				
	}
	//	scroller_vertical = new Scrolling.Scroller(document.getElementById("ScrollerVertical"), 13, 90, null, "Vertical");
	//	scrollbar_vertical = new Scrolling.Scrollbar(document.getElementById("ScrollbarVertical-Container"), scroller_vertical, new Scrolling.ScrollTween("Vertical"), "Vertical");
	scrollbar_vertical.update();
	scrollbar_horizontal.update();
//if (!requires_stacking) break;
}

function check_stack_up(sender, index)
{
	var i = bulletIndex;
	if ($a('div_bullet_timeline_' + i) != sender)
		i = bullet_selected;
	if ($a('div_bullet_timeline_' + i) != sender)
		i = index;
	
	var chapter_index = bullets[i][index_chapter];
	
	var requires_stacking = false;
	for (var k=0; k < bullets.length; k++)
	{
		if (bullets[k][index_chapter] != bullets[i][index_chapter]) continue;
		if (k == i || bullets[i][index_stack] != bullets[k][index_stack]) continue;
			
		//
		// Check if we need to stack up given element
		if (
			((bullets[i][index_start] < bullets[k][index_start]) && (bullets[i][index_end] > bullets[k][index_start]))
			||
			((bullets[k][index_start] < bullets[i][index_start]) && (bullets[k][index_end] > bullets[i][index_start]))
			)
			{
			bullets[k][index_stack]++;
			//
			// check if we need to create new row to accomodate
			
			var table = $a('table_chapter_timeline_outer');
		
			if (table.rows.length-1 < 1);//bullets[k][index_stack])
			{
				var row_index = 1;
				var row = table.insertRow(row_index);//table.rows.length);
				var cell = row.insertCell(0);
				cell.style.backgroundImage = "url(" + urlStylist + "/images/modules/videoresume/graytile.png);";
				cell.style.height = "30px;";
				
				//
				// Insert the content of the cell
				var s = '<table cellpadding="0" cellspacing="0" id="table_chapter_timeline_' + chapter_index + '_' + bullets[k][index_stack] + '" style="position:relative;">';
				s += '<tr>';
				s += 	'<td style="width:' + $a('cell_chapter_' + chapter_index + '_gray_' + (bullets[k][index_stack]-1)).style.width + '" id="cell_chapter_' + chapter_index + '_gray_' + bullets[k][index_stack] + '"></td>';
				s +=	'<td id="cell_chapter_' + chapter_index + '_blue_' + bullets[k][index_stack] + '" style="background-image: url(' + urlStylist + '/images/modules/videoresume/bluetile.png); height: 30px; width: ' + (parseInt($a('cell_chapter_' + chapter_index + '_blue_' + (bullets[k][index_stack]-1)).style.width)-0) +'px">';
				s +=		'<div style="float: left; background-image: url(' + urlStylist + '/images/modules/videoresume/blueleftcap.png); height: 30px; width: 4px;"></div>';
				s +=		'<div id="div_timeline_bullets_' + chapter_index + '_' + bullets[k][index_stack] + '">';
				s +=		'</div>';
				s +=	'</td>';
				s +=	'<td>';
				s +=		'<div style="float: right; background-image: url(' + urlStylist + '/images/modules/videoresume/bluerightcap.png); height: 30px; width: 4px;"/></div>';
				s +=    '</td>';
				s +=   '</tr>';
				s +=  '</table>';
				    
				cell.innerHTML = s;
				 
				row = $a('table_chapters').insertRow(row_index);
				cell = row.insertCell(0);
				cell.colSpan = 2;
				cell.style.height = "30px"
				cell.style.backgroundImage = "url(" + urlStylist + "/images/modules/videoresume/styler/chaptertile.png)";
				cell.innerHTML = "-";
			}
			//
			// Append child
			$a('div_timeline_bullets_' + chapter_index + '_' + bullets[k][index_stack]).appendChild($a('div_bullet_timeline_' + k));
			check_stack_up($a('div_bullet_timeline_' + k), k);
			
			
			requires_stacking = true;
		}
				
	}
//if (!requires_stacking) break;
}

/* Checks if there are any changes made that are unsaved */
function check_changes()
{
	
	if (mode == 'preview') return;
	//
	// Compare with query string
	var query_string = get_save_data();
	
	if (query_string != original_query_string)
	{
		$('#span_information').html("Unsaved changes !");
		save();
	}
	else
	{
		
		$('#span_information').html("");
	}
}

/* Scrolls down to given chapter */
function scroll_to_chapter(chapter_index)
{
	
	//
	// Find the position of given chapter
	//alert(chapter_index);
	var position = 0;
	for (var i=0; i < chapter_index; i++)
	{
		position += parseInt($a('cell_chapter_heading_' + i).style.height);
	//	alert(parseInt($a('cell_chapter_heading_' + i).style.height));
	}
	//alert(position);
	//position -= parseInt($a('timescale_handle').style.height);
	scrollbar_vertical.tweenTo(position);
}


//
// Drags the movie
function drag_movie()
{
/*
	$a('div_flash_top').style.left = Math.max(13, parseInt($a('div_flash_top').style.left)) + "px";
	$a('div_flash_top').style.top = Math.max(35, parseInt($a('div_flash_top').style.top)) + "px";
	$a('div_flash_top').style.left = Math.min(13 + 630 - parseInt($a('div_flash_top').style.width), parseInt($a('div_flash_top').style.left)) + "px";
	$a('div_flash_top').style.top = Math.min(35 + 379 - parseInt($a('div_flash_top').style.height), parseInt($a('div_flash_top').style.top)) + "px";
	
	$a('div_flash_top').style.top = Math.max(35, parseInt($a('div_flash_top').style.top)) + "px";
	
	$a('div_flash').style.left = parseInt($a('div_flash_top').style.left) + "px";
	$a('div_flash').style.top = parseInt($a('div_flash_top').style.top) + "px";
	*/
}




var savedTarget=null; // The target layer (effectively vidPane)
var orgCursor=null;   // The original Cursor (mouse) Style so we can restore it
var dragOK=false;     // True if we're allowed to move the element under mouse
var dragXoffset=0;    // How much we've moved the element on the horozontal
var dragYoffset=0;    // How much we've moved the element on the verticle
 
function moveHandler(e){
	if (e == null) {
		e = window.event
	}
	if (e.button<=1&&dragOK){
		
		savedTarget.style.left=e.clientX-dragXoffset+'px';
		savedTarget.style.top=e.clientY-dragYoffset+'px';
		drag_movie();
		return false;
	}
}

function cleanup(e) {
	document.onmousemove=null;
	document.onmouseup=null;
	savedTarget.style.cursor=orgCursor;
	dragOK=false;
}

function dragHandler(target){
	/*
      var htype='-moz-grabbing';
      
      if (e == null) { e = window.event; htype='move';} 
      var target = e.target != null ? e.target : e.srcElement;
      */

	var htype='-moz-grabbing';
	if (isIE)
		htype='move';
	if (target.id == "cell_movie")
	{
		target = target.parentNode.parentNode.parentNode.parentNode;	
	}
	//alert(target.innerHTML);
	orgCursor=target.style.cursor;
	if (target.className.indexOf("movable")>=0) {
		savedTarget=target;
		target.style.cursor=htype;
		dragOK=true;
		dragXoffset=/*e.clientX-*/parseInt(target.style.left);
		dragYoffset=/*e.clientY-*/parseInt(target.style.top);
		document.onmousemove=moveHandler;
		document.onmouseup=cleanup;
		return false;
	}
}
	 
//document.onmousedown=dragHandler;
	 
	 
function sizetest()
{
	var height1 = $a('sizetest_1').value;
	var height2 = $a('sizetest_2').value;
	for (var i=0; i < 4; i++)
	{
		$a('cell_chapter_heading_' + i).style.height = height1 + "px";
		$a('table_timeline_bullets_' + i + '_0').parentNode.parentNode.style.height = height2 + "px";
	}
}

// After Vertical Scroll
function onScrollVertical(x, y)
{

}

// After Horizontal Scroll
function onScrollHorizontal(x, y)
{
	x = isNaN(x) ? 0 : x;
	scroll_shift = x;
	
	// Change the beginning value of time above timeline
	
	if (!isNaN(total_duration) && total_duration > 0)
	{
		var total_width = $a('table_chapter_timeline_outer').offsetWidth;
		time_shift = (x * total_duration) / total_width;
		$a('span_start_time').innerHTML = get_time_format(time_shift);
		
		
		//
		if (totalTimeElapsed == -1) totalTimeElapsed = 0;
		var difference = totalTimeElapsed - time_shift;
		var new_slider_value = difference * time_scale / 600;
		
		
		if ((new_slider_value < 0 || new_slider_value > 1) && !time_scaling)
		{
			$a('movie_track').style.visibility = "hidden";
		}
		else
		{
			$a('movie_track').style.visibility = "visible";
			if (time_scaling) return;
			if (is_movie_handle_down)
			{
				
				onSliderSlide(slider.slider('value'));
			}
			else
			{
				if (!sliding_by_time)
				{
					sliding_by_time = true;
					slider.slider('value', new_slider_value);
					///slider.setValue(new_slider_value);
					sliding_by_time = false;
				}
			}
		}
		

	//var currentTime = (slider.getValue() * 600)/ time_scale + time_shift;
	//var time_format = get_time_format(currentTime);
	//$a('movie_progress').innerHTML = time_format;
		
	//
	// Check if the scrubber should be hidden
		
	}
}

// converts number of miliseconds to the format m:ss:msms
function get_time_format(currentTime)
{
	var milliseconds = Math.floor((100 * currentTime) % 100);
	if (milliseconds  < 10) milliseconds = "0" + milliseconds ;
	var seconds = Math.floor(Math.round(100*(currentTime))/100 % 60);
	var min = Math.floor(currentTime / 60);
	if (seconds < 10) seconds = "0" + seconds;
	return min + ":" + seconds + ":" + milliseconds ;
}

var is_movie_handle_down = false;
var movie_handle_auto_scroll_id;

// Occurs when the mouse button is pressed
function movie_handle_down()
{
	document.onmouseup = movie_handle_up;
	is_movie_handle_down = true;
	movie_handle_auto_scroll_id = setInterval(movie_handle_auto_scroll, 50);
}

// Occurs when the mouse button is released
function movie_handle_up()
{
	is_movie_handle_down = false;
	document.onmouseup = null;
	clearInterval(movie_handle_auto_scroll_id);
}

function movie_handle_auto_scroll()
{
	var v = slider.slider('value');
	if (v == 0 || v == 1)
	{
	
		var currentTime = ((-0.05 + v * 1.1) * 600)/ time_scale + time_shift;
		var sliderTime = (v * 600) / time_scale + time_shift;
		var differenceTime = currentTime - sliderTime;
		var total_width = $a('table_chapter_timeline_outer').offsetWidth;
		var scroll_by = (differenceTime * total_width / total_duration);
							
		var d = scroller_horizontal.getDimensions(); 
		scrollbar_horizontal.scrollTo(Math.min(d.twidth - d.stwidth - 24, d.x + scroll_by));
	//$a('div_buffering').innerHTML = (d.x + scroll_by) + " " + d.twidth;

	}
}

function onSliderSlide(v)
{
	
	// update time duration if not set
	if (durationMovie <= 0)
	{
		setDuration(durations[current_chapter]);
	}
	
	var currentTime = (v * 600)/ time_scale + time_shift;
	totalTimeElapsed = currentTime;
	var time_format = get_time_format(currentTime);
	
	$a('movie_progress').innerHTML = time_format;
	
	if (!sliding)
	{
		flash.pauseStylist();
		sliding = true;
	}
	
	
	//
	// Check if we are crossing the chapter border
	var next_chapter = current_chapter;
	while (next_chapter > 0 && currentTime < durations_shifts[next_chapter])
		next_chapter--;
	while (next_chapter < chapter_count-1 && currentTime > durations_shifts[next_chapter+1])
		next_chapter++;

	select_chapter(next_chapter, false);
	scroll_to_chapter(next_chapter);
	if (!playing) edit_mode();
	show_hide_all_bullets(null);
}

function flashError(msg)
{
//alert("Flash error: " + msg);
}

//
// rewinds the stylist and select previous chapter if clicked in proper time interval
//var rewind_time = new Date();
function rewind()
{
	//var current_time = new Date();
	//if (rewind_time.getSeconds() == current_time.getSeconds())
	if (timeMovie == 0)
	{
		if (current_chapter > 0)
		{
			var next_chapter = current_chapter-1;
			select_chapter(next_chapter);
			scroll_to_chapter(next_chapter);
			timeMovie = 0;
			setTime(0);
		}
		handleStylistButtonChange();
	}
	else
		flash.rewindStylist();
//rewind_time = new Date();
}

// moves forward the movie
function forward()
{
	if (record_mode == 'record_no_script')
	{
		setTime(durationMovie);
	}
	else
	{
		if (current_chapter < chapter_count - 1)
		{
			var next_chapter = current_chapter + 1;
			select_chapter(next_chapter);
			scroll_to_chapter(next_chapter);
			timeMovie = 0;
			setTime(0);
		}
		handleStylistButtonChange();
	}
}

// moves the chapters list within given area
var max_chapter_width = 390;

function move_chapters_list()
{
	//move_element($a('div_chapters_list'), 'chapter');
}

function move_bullets_constraint()
{
	for (var i=0; i < bullets.length; i++)
	{
		move_element($a("div_bullet_" + i), 'bullet');
	}
}

function move_element(div, type)
{
	var skin = skins[current_skin_index];
	
	// x and y of bullets area
	var x = skin[index_skin_bullets][0];
	var y = skin[index_skin_bullets][1];
	
	var div_x = parseInt(div.style.left);
	var div_y = parseInt(div.style.top);
	var div_width = div.offsetWidth;
	var div_height = div.offsetHeight;

	//alert(current_skin_index + " " + div_x + " " + div_y + " " + div_width + " " + div_height);
	//$a('div_buffering').innerHTML = (div.childNodes[0]);
	
	if (div_width > max_chapter_width)
		div.style.width = max_chapter_width + "px";
	
	if (div_x < x) div.style.left = x + "px";
	if (div_y < y) div.style.top = y + "px";
	if (div_x + div_width >= x + max_chapter_width) div.style.left = (x + max_chapter_width - div_width) + "px";
	if (div_y + div_height > y + 235) div.style.top = (y + 235 - div_height) + "px";
}

// check if we have proper chapter width, if too long, make it max_chapter_width so it wraps
function check_chapter_width()
{
	
	var div = $a('div_chapters_list');
	if (div.offsetWidth > max_chapter_width) 
		div.style.width = max_chapter_width + "px";
	else
		div.style.width = "";
}
	

//
// Shows or hides gridlines
function show_hide_gridlines(sender)
{
	$a('div_gridline').style.display = (sender.checked) ? "block" : "none";
}

// shows all or only these that are covered by timeline handle in pause mode
var show_all_bullets = false;
function show_hide_all_bullets(sender)
{
	if (sender != null)
		show_all_bullets = sender.checked;


	//
	// Check if we need to show / hide any element
	if (!playing)
	{
		
		for (var i=0; i < bullets.length; i++)
		{
			var bullet = bullets[i];
			var start = bullet[index_start];
			var end = bullet[index_end];
			//alert(previousTimeMovie + ' - ' + start + ' - ' + timeMovie);
			var div = $a('div_bullet_' + i);
			if ( ( (start <= timeMovie && end>= timeMovie) || show_all_bullets ) && !bullet[index_removed] && bullet[index_chapter] == current_chapter) 
			{
				div.style.display = "block";
			}
			else
			{
				div.style.display = "none";
			}
		}
	}
}

function test_move(sender)
{

	$a('div_test_move').style.left = sender.value + "px";
}



//
//
function bufferingStatus(state)
{
	if (state == "buffering")
		$a('div_buffering').innerHTML = "Buffering ...";
	else
		$a('div_buffering').innerHTML = "";
}


function showAddBullet()
{
	//$a('div_skins').style.display = "none";
	//$a('div_bullets_setup').style.display = "block";
        
	$('#div_bullets_setup').dialog("open");
	
}
function showSelectSkin()
{
//$a('div_skins').style.display = "block";
//$a('div_bullets_setup').style.display = "none";
}



function handleStylistButtonChange()
{
    if ( current_chapter == 0 && chapter_count == 1 )
    {
		$("#img_fastreverse").attr("src",urlStylist + "/modules/videoresume/images/OR20_PreviousSection_blank.png");
		$("#img_fastforward").attr("src",urlStylist + "/modules/videoresume/images/OR20_NextSection_blank.png");
		return;
    }

	if ( current_chapter == 0 || current_chapter == null)
	{
		$("#img_fastreverse").attr("src",urlStylist + "/modules/videoresume/images/OR20_PreviousSection_blank.png");
	}
	else
	{
		$("#img_fastreverse").attr("src",urlStylist + "/modules/videoresume/images/OR20_PreviousSection.png");
	}
	if ( current_chapter == chapter_count-1)
	{
		$("#img_fastforward").attr("src",urlStylist + "/modules/videoresume/images/OR20_NextSection_blank.png");
	}
	else
	{
		$("#img_fastforward").attr("src",urlStylist + "/modules/videoresume/images/OR20_NextSection.png");
	}
}

$(document).ready(function()
{
	handleStylistButtonChange();
});













function testAnimateIn()
{
	var div = $a('div_bullet_0');
	animateIn(div, 'Appear', 1);
}
function testAnimateOut()
{
	var div = $a('div_bullet_0');
	animateOut(div, 'Fade', 1);
}
function testAnimateShow()
{
	var div = $a('div_bullet_0');
	div.style.display = "";
}
function testAnimateHide()
{
	var div = $a('div_bullet_0');
	div.style.display = "none";
}
