// public variables used by multiple function

var gallery = [];

var compare_stack = [];

/**
 * Executed when document is finished loading elements into DOM
 */
var position_propery = 'backgroundPosition';
$(document).ready(function()
{

	$('#lietoti-iframe').load(function(){
        this.style.height = parseInt(this.contentWindow.document.body.offsetHeight + 20) + 'px';
    });


	if (typeof(first_intro_id) == 'number'){
		$('#intro-flash-tabs .loading').css(position_propery, 'left 0px');
		loadIntro(first_intro_id, true);
	}

	table_row_nr = 0;
	$('table.info tr').each(function(){
		table_row_nr++;
		if (table_row_nr % 2 == 1){
			$(this).addClass('odd');
		}else{
			$(this).addClass('even');
		}
	});

	/**
	 * Display confirmation dialog whenever link
	 * with className "confirm" is slicked
	 */
	$(".confirm").click(function(){
		return confirm("Vai tiešām vēlaties veikt šo darbību?");
	});

	// fixes weird bug
	$("#menu ul").show().hide();

	$("#menu li").mouseover(function(){
		$(this).find("> ul").show();
	});

	$("#menu li").mouseout(function(){
		$(this).find("> ul").hide();
	});

	$(".submenu").mouseover(function(){
		$(this).parent().find("> a").addClass("hover");
	});

	$("#intro-flash-tabs .tab").click(function(){
		loadIntro(this);

		return false;
	});

	$("#intro-flash-tabs .tab .link-container a").click(function(){
		document.location = this.href;
	});

	$(".submenu").mouseout(function(){
		$(this).parent().find("> a").removeClass("hover");
	});

	$(".tabs a").click(function(){
		$(".tabs td").removeClass("active");
		$(this).parent().addClass("active");

		$(".tabbed .content > div").hide();
		$("#"+$(this).attr("rel")).show();

		return false;
	});


	// fix lai nav nobīdījušās līnijas (#2022)
	if (navigator.userAgent.search(/msie/i)!= -1){
		padding = 0;
	}else if (navigator.userAgent.search(/Chrome/i)!= -1){
		padding = 0;
	}else if (navigator.userAgent.search(/Safari/i)!= -1){
		padding = 0;
	}else{
		padding = 21;
	}
	key = 0;
	$('table.spec1 td.desc').each(function() {
		$(this).css('height', ($($('table.spec2 td.desc')[key]).height() + padding) + 'px');
		key++;
	});
	// ---

	$(".zoom").append("<span></span>");

	$(".pop").fancybox();

	$("input.datepicker").datepicker({
		dateFormat: 'yy-mm-dd',
		dayNamesMin: ['Sv', 'Pi', 'Ot', 'Tr', 'Ce', 'Pi', 'Se'],
		firstDay: 1,
		monthNames: [
			'janvāris', 'februāris', 'marts', 'aprīlis', 'maijs', 'jūnijs', 'jūlijs',
			'augusts', 'septembris', 'oktobris', 'novembris', 'decembris'
		],
		nextText: 'vēlāk',
		prevText: 'agrāk',
		minDate: new Date()
	});
});

/**
 * Print email link (protection from spambots)
 * If javascript is disabled, nothing is visible
 *
 * @param string p1 Part 1 - this is username
 * @param string p2 Part 2 - this is domain and TLD
 */
function writemail(p1, p2)
{
	document.write("<a href='mailto:"+p1+"@"+p2+"'>"+p1+"@"+p2+"</a>");
}

var current_subintro_id = 0;
var mover_inside_element = false;
var zoom_animation_interval = 180;
var ajax_is_loading = false;

function animatePngSpinner(){
	if (ajax_is_loading){
		position = $('#intro-flash-tabs .loading').css(position_propery).split(' ');
		top_position = position[1].split('px');
		top_position = top_position[0];

		if (top_position - 31 == -248){
			$('#intro-flash-tabs .loading').css(position_propery, 'left 0px');
		}else{
			$('#intro-flash-tabs .loading').css(position_propery, 'left '+parseInt(top_position - 31)+'px');
		}
		setTimeout('animatePngSpinner()', 100);
	}
}

function animateFlashIntro(){
	$('#sub-intros .item .sub-intro-img').mouseenter(function(){
		//zoomoutSubTab('', true);
		this_element = this;
		$('#sub-intros .item .sub-intro-img').each(function(){
			if (this_element != this){
				//$(this).animate({'width': '89px', 'height': '50px'}, zoom_animation_interval);
				//$(this).parent().parent().children('.progress').css('height', '3px');
			}
		})

		//$(this_element).animate({'width': '154px', 'height': '86px'}, zoom_animation_interval);
		//$(this_element).parent().parent().children('.progress').css('height', '4px');
	});

	$('#sub-intros .item .sub-intro-img').mouseout(function(){
		sub_tab_id = $(this).parent().parent().attr('id');
		setTimeout('zoomoutSubTab("#'+sub_tab_id+'", false)', 1);
	});

	$('#sub-intros .item .progress-control, #sub-intros .item .progress').mouseenter(function(){
		mover_inside_element = true;
	})

	$('#sub-intros .item .progress-control, #sub-intros .item .progress').mouseout(function(){
		mover_inside_element = false;
	})
}

function zoomoutSubTab(sub_tab_id, unzoom_all){
	if (unzoom_all){
		//$('#sub-intros .item .sub-intro-img').animate({'width': '89px', 'height': '50px'}, zoom_animation_interval);
		//$('#sub-intros .item .sub-intro-img').parent().parent().children('.progress').css('height', '3px');
	}else if (!mover_inside_element){
		element = $(sub_tab_id+' img.sub-intro-img');

		//$(element).animate({'width': '89px', 'height': '50px'}, zoom_animation_interval);
		//$(element).parent().parent().children('.progress').css('height', '3px');
	}
}

function startSubIntroProgress(){
	$('#sub-intro-'+current_subintro_id+' .progress-control').removeClass('resume');
	$('#sub-intro-'+current_subintro_id+' .progress-control').addClass('pause');

	progress_width = $('#sub-intro-'+current_subintro_id+' .progress').css('width').replace('pt', '');
	progress_width = progress_width.replace('%', '');
	progress_width = progress_width.replace('px', '');

	progress_left_width_int = 98 - progress_width;

	progress_time = progress_left_width_int * 98;

	$('#sub-intro-'+current_subintro_id+' .progress').animate({'width': '98%'}, progress_time, null, function(){
		next_is_next = false;
		switch_done = false;
		$('#sub-intros .item').each(function(){
			if (next_is_next){
				next_is_next = false;
				switch_done = true;
				$(this).children('a.button-link').click();
			}else if ('sub-intro-'+current_subintro_id == this.id){
				next_is_next = true;
			}
		})
		if (!switch_done){
			$('#sub-intros .item:first a.button-link').click();
		}
	});
}

function toogleSubIntroProgress(){
	if ($('#sub-intro-'+current_subintro_id+' .progress-control').hasClass('pause')){
		$('#sub-intro-'+current_subintro_id+' .progress-control').removeClass('pause');
		$('#sub-intro-'+current_subintro_id+' .progress-control').addClass('resume');
		$('#sub-intro-'+current_subintro_id+' .progress').stop(false);
	}else{
		startSubIntroProgress();
	}
}

/**
 * Changes intro flash tab to passed tab
 *
 * @param element - tab element
 */
function loadIntro(element, onload){
	if (onload){
		tab_id = element;
		element = $('#tab-'+tab_id);
	}else{
		var element_id = element.id.split('-');
		tab_id = element_id[1];
	}

	if (!$(element).hasClass('active')){
		$('#tab-'+tab_id+' .loading').show();
		ajax_is_loading = true;
		animatePngSpinner();

		$.ajax({
			url: webroot+'start/ajax_intro/'+tab_id,
			cache: false,
			success: function(html){
				$("#sub-intros").html('');
				$("#intro-content").html(html);

				$.ajax({
					url: webroot+'start/ajax_subintros/'+tab_id,
					cache: false,
					success: function(html){
						$("#sub-intros").html(html);
						$('.link-container').hide();
						$('#intro-flash-tabs .tab').removeClass('active');
						$(element).addClass('active');
						$(element).children('.link-container').show();
						$('#tab-'+tab_id+' .loading').hide();
						ajax_is_loading = false;

						animateFlashIntro();
						$('#sub-intros .item:first a.button-link').click();
					}
				});
			}
		});
	}
}

function loadSubIntro(tab_id){
	$('#sub-intros .item .sub-intro-img').each(function(){
		$(this).attr('src', $(this).attr('src').replace('_active.jpg', '.jpg'));
	});

	var active_src = $('#sub-intro-'+tab_id+' .sub-intro-img').attr('src').replace('.jpg', '_active.jpg');
	$('#sub-intro-'+tab_id+' .sub-intro-img').attr('src', active_src);

	$('#sub-intros .item .sub-intro-img').removeClass('active');
	$('#sub-intro-'+tab_id+' .sub-intro-img').addClass('active');
	$('#sub-intros .item .progress-control').removeClass('resume');
	$('#sub-intros .item .progress-control').removeClass('pause');
	$('#sub-intros-container .item .progress').stop();
	$('#sub-intros-container .item .progress').css('width', '0');

	$('#sub-intro-'+tab_id+' .loading').show();

	$.ajax({
		url: webroot+'start/ajax_intro/'+tab_id,
		cache: false,
		dataType: 'script',
		success: function(html){
			current_subintro_id = tab_id;
			$("#ajax-intro #intro-content").html(html);
			$('#sub-intro-'+tab_id+' .loading').hide();

			animateFlashIntro();
			startSubIntroProgress();
		}
	});
}

/**
 * Load gallery item (image, flash, video)
 *
 * @param int n Item index in gallery array
 */
function loadGalleryItem(n)
{
	for (key in gallery){
		if (gallery[key]['id'] == n){
			gallery_item = gallery[key];
		}
	}

	if (typeof(gallery_item) != "undefined")
	{
		if (gallery_item["type"] == "image")
		{
			$("#big-intro-flash").empty().hide();
			$("#intro-controls").show();

			$("#big-intro").css("background-image", "url("+gallery_item["src"]+")");

			$("#big-intro p").text(gallery_item["title"]);

			$("#intro-controls .download").attr("href", webroot+"lv/gallery_images/download/"+gallery_item["id"]);
			$("#intro-controls .fullscreen").attr("href", webroot+"img/galleries/large/"+gallery_item["filename"]);
		}
		else
		if (gallery_item["type"] == "flash")
		{
			var so = new SWFObject(gallery_item["src"], "introflash", "780", "440", 8, "#eeeeee");
			so.addParam("wmode", "opaque");
			so.write("big-intro-flash");

			$("#big-intro").css("background-image", "none");
			$("#intro-controls").hide();
			$("#big-intro-flash").show();
		}
		else
		if (gallery_item["type"] == "video")
		{
			var so = new SWFObject(webroot+"swf/ENGInE_media_player.swf", "introflash", "780", "440", 8, "#000000");
			so.addParam("wmode", "opaque");
			so.addParam("allowFullScreen", "true");
			so.addParam("Play", "true");
			so.addParam("base", webroot+"swf/");
			so.addParam("FlashVars", "xml="+webroot+"xml/media_player.xml&amp;flv_high_bandwidth="+gallery_item["src"]+"&amp;flv_medium_bandwidth="+gallery_item["src"]+"&amp;flv_low_bandwidth="+gallery_item["src"]+"&amp;subtitles_xml="+webroot+"xml/subtitles.xml&amp;static_image="+webroot+"img/galleries/medium/"+gallery_item["filename"].replace(/.flv/, ".jpg"));
			so.write("big-intro-flash");

			$("#big-intro").css("background-image", "none");
			$("#intro-controls").hide();
			$("#big-intro-flash").show();
		}

		$(".minigallery a").removeClass("active");
		$("#gallery-item-"+n+" a").addClass("active");
	}
}


function openOption(el, id)
{
	if ($("#"+id).is(":visible"))
	{
		$(".option-box a").removeClass("active");
		$("#"+id).hide();
	}
	else
	{
		$(".option-box .info").hide();

		$(".option-box a").removeClass("active");
		$(el).addClass("active");

		$("#"+id).show();
		// w/o this, zoom icon doesn't show up
		$("#"+id+" a").focus().blur();
	}
}

/**
 * Show/hide specified category's entries from spec table
 * If category_id = 0, show all categories
 *
 * @param int category_id Category ID
 */
function changeFeaturesCategory(category_id)
{
	if (category_id == "0")
	{
		$(".spec tbody").show();
	}
	else
	{
		$(".spec tbody").hide();
		$(".category-group-"+category_id).show();
	}
}


/**
 * Scroll n columns in spec table
 *
 * @param int n Number of columns to scroll to right (may be negative to scroll left)
 */
function MoveSeriesFeaturesCol(n)
{
	if (spec_td_c <= 3) { return; }
	if (n < 0 && spec_pos <= 0) { return false; }
	if (n > 0 && spec_pos >= spec_td_c - 3) { return false; }

	spec_pos += n;

	if (spec_pos <=0 )
	{
		$("#spec-prev").addClass("spec-nav-disabled");
	}
	else
	{
		$("#spec-prev").removeClass("spec-nav-disabled");
	}

	if (spec_pos >= spec_td_c - 3)
	{
		$("#spec-next").addClass("spec-nav-disabled");
	}
	else
	{
		$("#spec-next").removeClass("spec-nav-disabled");
	}

	$("#spec-data-container").animate({ left: "-"+(spec_pos * 105)+"px" }, 500);
}

/**
 * Add model to compare stack. If specified model already
 * exists in stack, remove it
 *
 * @param int id Model ID
 */
function addToCompareStack(id, modelTitle, seriesTitle)
{
	// check if given model already exists in stack
	for (var i in compare_stack)
	{
		if (compare_stack[i].id == id)
		{
			removeFromCompareStack(i);
			return;
		}
	}

	if (compare_stack.length >= 3)
	{
		return;
	}

	compare_stack[compare_stack.length] = {"id":id, "modelTitle":modelTitle, "seriesTitle":seriesTitle}

	$("#stack-action-"+id).removeClass("add").addClass("remove");

	redrawCompareStack();
}

/**
 * Remove model from stack
 *
 * If entry is removed somewhere from the middle
 * of stack, move every next item back, so indexes
 * stay the same (0, 1, 2)
 *
 * @param int n Stack number (0-2)
 */
function removeFromCompareStack(n)
{
	var tmp_compare_stack = [];

	var index = 0;

	for (var i in compare_stack)
	{
		if (i != n)
		{
			if (typeof(compare_stack[i]) != "undefined")
			{
				tmp_compare_stack[index++] = compare_stack[i];
			}
		}
		else
		{
			$("#stack-action-"+compare_stack[i].id).removeClass("remove").addClass("add");
		}
	}

	compare_stack = tmp_compare_stack;

	redrawCompareStack();
}

/**
 * Show every model in JS stack
 */
function redrawCompareStack()
{
	for (var n = 1; n < 4; n++)
	{
		$("#car-item-"+n+" img").remove();
		$("#car-item-"+n+" .model-info").hide();
	}

	for (var i in compare_stack)
	{
		$("#CarSeriesId"+i).val(compare_stack[i].id);

		$("#car-item-"+(parseInt(i)+1)).prepend("<img src='"+webroot+"img/models/small/"+compare_stack[i].id+".png' alt='"+compare_stack[i].modelTitle+"' />");

		$("#car-item-"+(parseInt(i)+1)+" .model-name").text(compare_stack[i].modelTitle);
		$("#car-item-"+(parseInt(i)+1)+" .series-name").text(compare_stack[i].seriesTitle);
		$("#car-item-"+(parseInt(i)+1)+" .model-info").show();
	}

	if (compare_stack.length < 2)
	{
		// disable car comparison button
		$(".submit input").attr("disabled", "disabled").addClass("disabled");
	}
	else
	{
		// enable car comparison button
		$(".submit input").removeAttr("disabled").removeClass("disabled");
	}
}
