var parinkta = '';
var kainos_x = 0;
var kainos_y = 0;
var focus_field = '';
var form_errors = [];
var dialog_height = 0;
var timeTracker = new TimeTracker();
var unload_trigger = 0;
var kaina;
var overlay_opened = 0;
var debug_log_id = 0;
var debug_label = undefined;
var last_clicked = '';

function cross(x, y) {
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec('cross('+x+', '+y+')');
	}
	
	$('.head').eq(x).addClass('stulpelis');
	
	$('.kaina').each(function(){
			
		if ( $(this).index() == x ) {
			$(this).addClass('stulpelis');
		}
	});
	
	$('.row').eq(y).addClass('eilute');
	
	$('.row').eq(y).find('.kaina').eq(x - 1).addClass('focus');
}

$(document).ready(function() {
	
	//$().error(err_handler);
		
	var kainu_lentele = $('.kaina').hover(function(){
		
		index = $(this).index();
		
		$('.kaina').each(function(){
			
			if ( $(this).index() == index ) {
				$(this).addClass('stulpelis');
			}
		});
		
		$('.head').eq(index).addClass('stulpelis');
		
		$(this).parent('.row').addClass('eilute');
		
		$(this).addClass('focus');
		
		$(this).removeClass('locked');
		
	}).mouseout(function(){
		
		if ( last_clicked != $(this).text() ) {
			$('.eilute, .lentele .focus, .stulpelis').removeClass('eilute focus stulpelis');
		}
		
		if ( kainos_y != 0 && kainos_x != 0 || last_clicked.length > 0) {
			cross(kainos_x, kainos_y);
		}
		
	}).click(function() {
		
		last_clicked = $(this).text();
		
		if ( typeof(inpage) != 'undefined' ) {
			return true;
		}
		
		if ( kainos_x != 0 && kainos_y != 0 ) {
			
			$('.head').eq(kainos_x).removeClass('stulpelis');
	
			$('.kaina').each(function(){
					
				if ( $(this).index() == kainos_x ) {
					$(this).removeClass('stulpelis');
				}
			});
			
			$('.row').eq(kainos_y).removeClass('eilute');
			
			$('.row').eq(kainos_y).find('.kaina').eq(kainos_x - 1).removeClass('focus');
		}
		
		var savaites = $(this).index();
		
		if ( debug == true ) {
			$('#kl_notification').html($(this).index());
		}
		
		kainos_x = $(this).index();
		kainos_y = $(this).parent('.row').index() / 2 - 1;
		
		$('.eilute, .lentele .focus, .stulpelis').removeClass('eilute focus stulpelis');
		cross(kainos_x, kainos_y);
		
		tirazas = $(this).parent('.row').find('.tirazas').text();
		
		if ( $('.post h2:first').text().match(/skraju/gi) ) {
			tipo = 'skrajučių';
		}
		else if ( $('.post h2:first').text().match(/lankst/gi) ) {
			tipo = 'lankstinukų';
		}
		else if ( typeof( ko_tokiu ) != 'undefined' ) {
			tipo = ko_tokiu;
		}
		else {
			tipo = 'lankstinukų';
		}
		
		
		
		oKaina = $(this).text();
		kaina = parseInt(oKaina.replace(/[^0-9]/g, ''));
		kainos_index = $(this).index();
		
		oPigiausia = $(this).parent('.row').find('.kaina:last');
		pigiausia = parseInt( oPigiausia.text().replace(/[^0-9]/g, '') );
		
		brangiausia = parseInt( $(this).parent('.row').find('.kaina:first').text().replace(/[^0-9]/g, '') );
		
		//kaina_append = '<h3 id="taupymo_pasiulymas">Sutaupote <strong>' + (brangiausia - kaina) + ' Lt</strong></h3>';
		kaina_append = 'Sutaupote <strong>' + (brangiausia - kaina) + ' Lt</strong>';
		
		var pristatymo_data = $('.head').eq( kainos_index ).text();

		kainu_info_html = '<h4>' + tirazas + ' vnt. ' + naudojamas_formatas + ' ' + tipo + '</h4><br />Pristatymas <b>' + pristatymo_data + '</b> d.<br />Kaina be PVM: <b>' + oKaina + '</b>';
		
		$('#pristatymo_data').html( pristatymo_data );
		$('#preke_kiekis').html( tirazas + ' vnt.');
		
		$.get('/maketo_data.php', {pristatymas: pristatymo_data}, function(maketas){
			$('#maketo_data').html( maketas );
		});
		
		var kaina_su_pvm = Math.ceil( kaina * 1.21 );
		
		//if ( debug == true ) {
			
			if ( savaites == 1 ) {
				var savaiciu_str = 'savaitės';
			}
			else if ( savaites == 5 ) {
				var savaiciu_str = 'mėnesio';
			}
			else {
				var savaiciu_str = savaites + ' savaičių';
			}
			
			var info_message = tirazas + ' vnt. ' + naudojamas_formatas + ' ' + tipo + ' pagaminsime po ' + savaiciu_str + '. Kaina su PVM: ' + formatuok( kaina_su_pvm ) + ' ' + money_sign;
			
			if ( debug == true ) {
				//info_message += '<button class="rounded red"><span>Užsakyti</span></button>';
				//info_message += '<div id="uzsakyti_mygtukas">Užsakyti</div>';
			}
			
			$('#kl_notification').html(info_message);
			
			if ( debug == true ) {
				//$('#uzsakyti_mygtukas').corner("round 4px");
			}
		//}
		
		$('#viso_kaina_virsus').html( formatuok( kaina_su_pvm ) + ' ' + money_sign );
		$('#viso_kaina_sask').html( formatuok( kaina_su_pvm ) + ' ' + money_sign );
		$('#kaina_be_pvm').html( formatuok( kaina ) + ' ' + money_sign );
		$('#kaina_pvm').html( formatuok( kaina_su_pvm - kaina ) + ' ' + money_sign );
		
		$('#data').val( pristatymo_data );
		$('#formatas').val( naudojamas_formatas );
		$('#tirazas').val( tirazas );
		
		if ( typeof(kur_jie) != 'undefined' ) {
			$('#l_tipas').val( kur_jie );
		}
		
					
		if ( $('#kainu_info').text() != '' ) {
			$('#kainu_info').html(kainu_info_html);
		}
		else {
			$('<div/>', {
				id: 'kainu_info',
				html: kainu_info_html
			}).appendTo('#po_lentele_kaire');
		}

		
		$('#kainu_info').append('<div><button class="rounded" id="checkout"><span>Užsakyti</span></button></div>');
		$('#checkout').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
			
			if ( typeof ClickTaleExec == 'function' ) {
				ClickTaleExec("openDialog()");
			}
			
			openDialog();
		});
		
		$('#po_lentele_kaire').animate({ backgroundColor: "#E2FFD7" }, 700 );
	});
	
	$('.reset_form').click(function(e){
		e.preventDefault();
		trackCancel();
		closeWindow();
		clearErrors();
	});
	
	$('#patvirtinimo_forma').submit(function(e){
		e.preventDefault();
	
		email_pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		
		$('#name, #surname, #email, #phone').each(function(){
			$(this).keyup(function(){
				if ( $(this).val().length > 0 ) {
					$(this).removeClass('field_error');
				}
			});
		});
		
		if ( $('#name').val().length == 0 || $('#surname').val().length == 0 || $('#email').val().length == 0 || $('#phone').val().length == 0 ) {
			
			markErrors();	
			showErrors();
		}
		else {
			$('#error_holder').hide();
			var form_data = $(this).serialize();
			var anime_height = $('#dialog').height() - $('#patvirtinimo_forma').height() - $('#form_status').height() + 20;
						
			$.ajax({
				type: "POST",
				url: "/uzsakymo_patvirtinimas.php",
				async: false,
				data: form_data,
				success: function(return_html) {				
					$('#uzsakymas_return').addClass('pull_down').html(return_html);
					$('#patvirtinimo_forma, #form_status').hide();

					$('#dialog').animate({height: anime_height }, 333);
					$('html,body').animate({scrollTop: 0}, 54);
					trackConfirm();
				}
			});
		}
	});
	
	dialog_height = $('#dialog').height();
	
	$(window).bind('beforeunload', function() {
		if ( unload_trigger == 0 ) {
			unload_events();
			unload_trigger = 1;
		}
	});
});

function openDialog() {
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("openDialog()");
	}
	
	var id = '#dialog';

	//Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	//Set height and width to mask to fill up the whole screen
	$('#mask').css({'width':maskWidth,'height':maskHeight});
	
	//transition effect		
	//$('#mask').fadeIn(1000);
	$('#mask').fadeTo(200, 0.6);

	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();
          		
	if ( typeof(dialog_height) != 'undefined' && dialog_height != $('#dialog').height() ) {
		$('#dialog').height(dialog_height);
	}
	
	//Set the popup window to center
	$(id).css('top',  winH/2-$(id).height()/2);
	$(id).css('left', winW/2-$(id).width()/2);
	
	$('#patvirtinimo_forma, #form_status').show();

	//transition effect
	$(id).fadeIn(300); 
	
	$(id + ' form input[type=text]:first').focus();
	
	var needed_height = $('#dialog').height() + $('#dialog').offset().top;
	
	if ( needed_height > $(window).height() ) {
		$('html,body').animate({scrollTop: 10}, 200);
	}
	
	trackOpen();
}

function closeWindow(){
	
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("closeWindow()");
	}
	
	$('#mask, .window').hide();
	$('.window input[type=text]').each(function(){
		$(this).val('');
	});
	$('#uzsakymas_return').removeClass('pull_down').html('');
	overlay_opened = 0;
}

function close_window() {
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("close_window()");
	}
	
	$('#mask, .window').hide();
}

function formatuok( kaina ) {
	
	return number_format( kaina, 0, '.', ' ' );
	
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function markErrors() {
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("markErrors()");
	}
	
	if ( $('#name').val().length == 0 ) {
		markError('name', 'vardą');
	}
	
	if ( $('#surname').val().length == 0 ) {
		markError('surname', 'pavardę');
	}
	
	if ( $('#email').val().length == 0 ) {
		markError('email', 'el. pašto adresą');
	}
	else if ( ! email_pattern.test( $('#email').val() ) ) {
		markError('email', 'teisingą el. pašto adresą');
	}
	
	if ( $('#phone').val().length == 0 ) {
		markError('phone', 'telefono numerį');
	}
}

function markError(name, error_message) {
	if ( focus_field.length == 0 ) {
		focus_field = name;
	}

	form_errors[form_errors.length] = error_message;
}

function clearErrors() {
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("clearErrors()");
	}
	
	$('.field_error').each(function(){
		$(this).removeClass('field_error');
	});
	$('#form_status').html('').removeClass('active');
}

function format_error_message(arr) {
	
	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("format_error_message(" + arr + ")");
	}
	
	var last = arr[arr.length - 1];
	
	mod_arr = arr;
	
	mod_length = mod_arr.length;
	
	mod_arr.length = mod_length - 1;
	
	if ( mod_arr.length > 1 ) {
		join_string = ' ir ';
	}
	else {
		join_string = '';
	}
	
	error_msg = mod_arr.join(', ') + join_string + last;
	
	return error_msg;
}

function showErrors() {

	if ( typeof ClickTaleExec == 'function' ) {
		ClickTaleExec("showErrors()");
	}

	if ( form_errors.length > 0 ) {
		
		error_message = 'Įveskite ';
	
		error_message += format_error_message(form_errors);
		
		$('#form_status').html(error_message).addClass('active');
		
		if ( focus_field.length > 0 ) {
			$('#' + focus_field).focus();
			focus_field = '';
		}
		
		form_errors = [];
	}
}

function unload_events() {
	if ( overlay_opened == 1 ) {
		trackRunaway();
	}
}

function trackOpen() {
	overlay_opened = 1;
	
	_gaq.push(['_trackEvent', 'Overlay-Forma', 'Parodyta-Open', create_label(), kaina]);
	timeTracker._recordStartTime();
	debug_track('trackOpen');
}

function trackConfirm() {
	timeTracker._recordEndTime();
	_gaq.push(['_trackEvent', 'Overlay-Forma', 'Patvirtinti-Click', create_label(), kaina]);
	_gaq.push(['_trackEvent', 'Laiko-Matavimas', 'Patvirtinti-Click', create_label(), trackedTime()]);
	
	overlay_opened = 0;
	debug_track('trackConfirm');
}

function trackCancel() {	
	timeTracker._recordEndTime();
	_gaq.push(['_trackEvent', 'Overlay-Forma', 'Atšaukti-Click', create_label(), kaina]);
	_gaq.push(['_trackEvent', 'Laiko-Matavimas', 'Atšaukti-Click', create_label(), trackedTime()]);
		
	overlay_opened = 0;
	debug_track('trackCancel');
}

function trackRunaway() {			
	timeTracker._recordEndTime();
	_gaq.push(['_trackEvent', 'Overlay-Forma', 'Pabėgo-Escape', create_label(), kaina]);
	_gaq.push(['_trackEvent', 'Laiko-Matavimas', 'Pabėgo-Escape', create_label(), trackedTime()]);
	
	debug_track('trackRunaway');
}

function trackedTime(){
	var total_time = parseInt( ( timeTracker.stopTime_ - timeTracker.startTime_ ) / 1000 );
	
	debug_track('trackedTime(' + total_time + ')');
	
	return total_time;
}

function create_label() {
	
	if ( kainos_index < 10 ) {
		kainos_index = '0' + kainos_index;
	}
	
	label_tirazas = tirazas.replace(/[^0-9]/, '');
	
	gramatura = 170;
	
	label = 'T:' + label_tirazas + ' / F:' + naudojamas_formatas + ' / G:' + gramatura + ' / P:' + kainos_index + ' / S:' + savaite;
	return label;
}

function debug_track(s_log) {
	//$.get("/aivaro/debug_log.php", { log: s_log, hash: s_hash, hash_sum: i_hash });
}

function fb_like(fb_url) {
	$('#facebook_frame').html('<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.skrajutes.lt%2F' + fb_url + '&amp;layout=standard&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=lucida+grande&amp;colorscheme=light" scrolling="no" frameborder="0" class="fb"></iframe>');
}
