//system values
var menuDelay = 800;
var sceneWidth = 960;
var sceneMargins = 1000;
var minMarkerMargin = 48;
var maxMarkerMargin = 403;
var flareWidth = 958;
var flareInterval = 300;
var menuCount = 5;
var keysWorking = true;
var kkeys = [], konami = "38,38,40,40,37,39,37,39,66,65";

var panelIds = ['Pirmas', 'Antras', 'Trecias', 'Ketvirtas', 'Penktas']
                
var serviceDetails = {
	'flash': {
			left: 79,
			top: 350,
			size: 145
		},
	'software': {
			left: 41,
			top: 156,
			size: 145
		},
	'website': {
			left: 169,
			top: 85,
			size: 145
		},
	'logo': {
			left: 492,
			top: -3,
			size: 117
		},
	'print': {
			left: 663,
			top: 52,
			size: 117
		},
	'seo': {
			left: 810,
			top: 206,
			size: 84
		},
	'photo': {
			left: 755,
			top: 374,
			size: 145
		}
};

jQuery.validator.addMethod("valueNot", function(value, element, params) { 
	return value != params; 
	}, 'Something\'s wrong with the value');
                
//init actions
jQuery(document).ready(function() {
	jQuery('#loader').hide();
	
	adjustSpace();
	
	setTimeout('updateMarkerPosition();', 800);
	
	jQuery('#Uzklausa, #MeniuWrap, #MainWrap').show();
	
	jQuery(window).resize(function() {
		adjustSpace();
	});

	jQuery(window).scroll(function() {
		updateMarkerPosition();
	});
	
	jQuery('div#mainMenu > a[class!=Lang]').click(function() {
		var tmpId = jQuery(this).attr('rel');
		scrollToId(tmpId);
		return false;
	});
	
	jQuery(document).bind('keydown', 'ctrl+right', function() {
		stepThroughMenu(true);
	});
	
	jQuery(document).bind('keydown', 'ctrl+left', function() {
		stepThroughMenu(false);
	});
	
	jQuery(document).keydown(function(e) {
		kkeys.push( e.keyCode );
		if ( kkeys.toString().indexOf( konami ) >= 0 ){
			jQuery(document).unbind('keydown',arguments.callee);  
		    jQuery('html, body').animate({'background-color': '#72C5A6'}, 3000);
		}  
	});
	
	jQuery('#contactsForm').validate({
		errorClass: 'error',
		errorPlacement: function(error, element) { },
		focusInvalid: false,
		invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				
				if (errors) {
					jQuery('div#contactsFormError').show();
				} else {
					jQuery('div#contactsFormError').hide();
				}
			},
		rules: {
				name: {
					required: true,
					valueNot: ruleValName
				},
				email: {
					required: true,
					email: true
				},
				comment: {
					required: true,
					valueNot: ruleValComment
				}
			},
		showErrors: function(errorMap, errorList) {
				var errors = this.numberOfInvalids();
				
				if (errors) {
					jQuery('div#contactsFormError').show();
				} else {
					jQuery('div#contactsFormError').hide();
				}
				
				this.defaultShowErrors();
			},
		submitHandler: function(form) {
				jQuery(form).ajaxSubmit(function (a, b) {
					if (b == 'success' && a == 'OK')
					{
						jQuery(form).resetForm();
						jQuery('#contactsFormSent').show();
						setTimeout('jQuery(\'#contactsFormSent\').fadeOut(800);', 3000);
					}
					else
					{
						jQuery('#contactsFormNotSent').show();
						setTimeout('jQuery(\'#contactsFormNotSent\').fadeOut(800);', 3000);
					}
				});
			}
	});
	
	if (currLang == 'lt')
	{
		jQuery('#topFormDeadline').datepicker({
			dateFormat: 'yy-mm-dd',
			firstDay: 1,
			buttonImage: '/img/s.gif',
			showOn: 'both',
			minDate: new Date(),
			showMonthAfterYear: true,
			currentText: 'Šiandien',
			dayNames: ['Sekmadienis', 'Pirmadienis', 'Antradienis', 'Trečiadienis', 'Ketvirtadienis', 'Penktadienis', 'Šeštadienis'],
			dayNamesMin: ['S', 'P', 'A', 'T', 'K', 'P', 'Š'],
			dayNamesShort: ['Sek', 'Pir', 'Ant', 'Tre', 'Ket', 'Pen', 'Šeš'],
			monthNames: ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'],
			monthNamesShort: ['Sau', 'Vas', 'Kov', 'Bal', 'Geg', 'Bir', 'Lie', 'Rgp', 'Rgs', 'Spa', 'Lap', 'Gru'],
			nextText: 'Kitas',
			prevText: 'Ankstesnis'
		});
	}
	else
	{
		jQuery('#topFormDeadline').datepicker({
			dateFormat: 'yy-mm-dd',
			firstDay: 1,
			minDate: new Date(),
			showMonthAfterYear: true
		});
	}
	
	jQuery('#topForm').validate({
		errorClass: 'error',
		errorPlacement: function(error, element) { },
		focusInvalid: false,
		invalidHandler: function(form, validator) {
				var errors = validator.numberOfInvalids();
				
				if (errors) {
					jQuery('div#topFormError').show();
				} else {
					jQuery('div#topFormError').hide();
				}
			},
		rules: {
				name: {
					required: true,
					valueNot: ruleValContactPerson
				},
				email: {
					required: true,
					email: true
				},
				phone: {
					required: true,
					valueNot: ruleValPhone
				},
				comment: {
					required: true,
					valueNot: ruleValProjectDesc
				}
			},
		showErrors: function(errorMap, errorList) {
				var errors = this.numberOfInvalids();
				
				if (errors) {
					jQuery('div#topFormError').show();
				} else {
					jQuery('div#topFormError').hide();
				}
				
				this.defaultShowErrors();
			},
		submitHandler: function(form) {
				jQuery(form).ajaxSubmit(function (a, b) {
					if (b == 'success' && a == 'OK')
					{
						jQuery(form).resetForm();
						jQuery('#topFormSent').show();
						setTimeout('jQuery(\'#topFormSent\').fadeOut(800); if (jQuery(\'#Uzklausa div.forma, #Uzklausa div.forma_en\').is(\':visible\')) toggleTopForm();', 3000);
					}
					else
					{
						jQuery('#topFormNotSent').show();
						setTimeout('jQuery(\'#topFormNotSent\').fadeOut(800);', 3000);
					}
				});
			}
	});
	
	jQuery('#portfoliothumbs').jScrollHorizontalPane({
		resize: false,
		scrollbarHeight:25,
		showArrwos: false
	});
	
	jQuery('#portfoliocarousel').jcarousel({
		initCallback: porfoliocarousel_initCallback,
		itemVisibleInCallback: {
			  onBeforeAnimation: porfoliocarousel_itemopened
			},
        scroll: 1
    });
});

function porfoliocarousel_initCallback(carousel) {
    jQuery('#portfoliothumbs div.Thumb > a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).attr('rel')));
        return false;
    });
}

function porfoliocarousel_itemopened(carousel, li, index, state) {
	jQuery('#portfoliothumbs div.Thumb > a > img').removeClass('highlighted');
	jQuery('#portfoliothumbs div.Thumb > a > img#portfolioThumb_' + index).addClass('highlighted');

	var p1 = (index - 1) * 135;
	var p2 = (index * 135) - 7;

	var offs = p1 - 271;
	
	if (offs < 0)
		offs = 0;
	
	if (offs > (jQuery('#portfoliothumbs > div').width() - 670))
		offs = jQuery('#portfoliothumbs > div').width() - 670;
	
	jQuery('#portfoliothumbs')[0].scrollTo(offs);
}

function scrollToId(id)
{
	if (id != 'Trecias')
		closeServices();
	
	var pos = jQuery('div#' + id).position();
	
	jQuery(document).scrollTo({left:pos.left + 'px'}, {
		axis: 'x',
		duration: menuDelay
	});
}

function adjustSpace()
{
	var tmp;
	tmp = getAllPanels();
	
	sceneMargins = parseInt((jQuery(window).width() - sceneWidth) / 2);
	sceneMargins = sceneMargins < 0 ? 0 : sceneMargins;
	
	tmp.css('margin', '0px ' + sceneMargins + 'px 0px ' + sceneMargins + 'px');
	
	jQuery('div#MainWrap, div#LensFlare').css('width', (5 * (sceneWidth + 2 * sceneMargins)) + 'px');
	
	updateMarkerPosition();
}

function getAllPanels()
{
	return jQuery('div#Pirmas, div#Antras, div#Trecias, div#Ketvirtas, div#Penktas');
}

function updateMarkerPosition()
{
	var availableWidth = jQuery(document).width() - jQuery(window).width();
	var scrolled = jQuery(window).scrollLeft() / availableWidth;
	if (isNaN(scrolled))
		scrolled = 0;
	var margin = parseInt(minMarkerMargin + (maxMarkerMargin - minMarkerMargin) * scrolled);
	jQuery('div#mainMenu > img.Rodykle').css('margin-left', margin + 'px');
	var lensLeft = parseInt(((jQuery(window).width() - flareWidth) / 2) - (flareInterval / 2) + (flareInterval * scrolled));
	var lensTop = jQuery(document).height() - 580
	lensTop = parseInt(lensTop > 0 ? lensTop / 2 : lensTop) + 5;
	jQuery('div#LensFlare').css('background-position', lensLeft + 'px ' + lensTop + 'px');
	
	var marg = parseInt(jQuery(window).height() / 2);
	marg = marg > 290 ? 290 : marg;
	jQuery('#MainWrap').css('margin-top', '-' + marg + 'px');
	
	marg = 290;
	
	if (jQuery(document).height() <= 581)
		marg = (parseInt(jQuery(window).height() / 2) + jQuery(window).scrollTop());
	
	jQuery('#Uzklausa').css('margin-top', '-' + marg + 'px');
	
	marg = 240;
	
	if (jQuery(document).height() <= 581)
		marg += 290 - (parseInt(jQuery(window).height() / 2) + jQuery(window).scrollTop());
	
	jQuery('#MeniuWrap').css('margin-top',  marg + 'px');
}

function stepThroughMenu(right)
{
	if (keysWorking)
	{
		keysWorking = false;
		var availableWidth = jQuery(document).width() - jQuery(window).width();
		var scrolled = jQuery(window).scrollLeft() / availableWidth;
		
		var menuNo = Math.round(scrolled * (menuCount - 1));
		
		scrolled = Math.round(100 * scrolled); 
		
		if (right)
		{
			if (scrolled >= Math.round(100 * menuNo * (1 / (menuCount - 1))))
				menuNo++;
		}
		
		if (!right)
		{
			if (scrolled <= Math.round(100 * menuNo * (1 / (menuCount - 1))))
				menuNo--;
		}
		
		menuNo++;
		
		menuNo = menuNo > menuCount ? menuCount : menuNo;
		menuNo = menuNo < 1 ? 1 : menuNo;
		
		menuNo--;
		
		scrollToId(panelIds[menuNo]);
		setTimeout('keysWorking = true', menuDelay)
	}
}

function toggleTopForm()
{
	var frm = jQuery('#Uzklausa div.forma, #Uzklausa div.forma_en');
	
	if (frm.is(':visible'))
	{
		jQuery('#topForm').fadeOut('fast', function() {
				frm.slideUp('slow');
			});
	}
	else
	{
		closeServices();
		
		frm.slideDown('slow', function() {
				jQuery('#topForm').fadeIn('fast');
			});
	}
}

function openService(service)
{
	var details = serviceDetails[service];
	
	jQuery('#servicesHighlight').fadeOut(servicesSpeed, function() {
		jQuery('#servicesTextHolder').html(jQuery('#' + service + 'ServiceInfo').html());
		jQuery('#servicesTextHolder').fadeIn(servicesSpeed);
		jQuery(this).css({
			marginLeft: details['left'],
			marginTop: details['top'],
			width: details['size']
		}).fadeIn(servicesSpeed);
	});

	
}

function closeServices()
{
	jQuery('#servicesHighlight').fadeOut(servicesSpeed);
	jQuery('#servicesTextHolder').fadeOut(servicesSpeed);
}
