window.onload = function(){
	// plotis
	var plotis = getWidth();
	setWidth('lights', plotis);
	setWidth('container', plotis);
	
	// vertikalus lygiavimas
	valign('site_lefter', 0, 0);
	valign('container', 45, 45);
	
	//scroll clickai
	addSlideClicks();
	
	if($('dovanu_kodas')) {
		 $('dovanu_kodas').observe('keyup', tikrinti_koda);
	}
	
	// ar kreipiamiasi i kazkokia preke
	var hash = window.location.hash.substr(1);
	if(hash > 0) {
		var preke = $('preke_'+hash);
		if(preke) {
			var blokas = preke.up(1);
			var blokas_id = parseInt(blokas.readAttribute('id').gsub("blokas_",""));
			toggle_vidinis(blokas_id, hash, lid);
		}
	}
	
}

// po resize
window.onresize = function() {
 	valign('site_lefter', 0, 0);
	valign('container', 45, 45);
}


// stebim paspaudimus
function addSlideClicks() {
	$$('.rodykle1 img').each(function (el) {
	    $(el).observe('click', scroll_kairen);
	});
	$$('.rodykle2 img').each(function (el) {
	    $(el).observe('click', scroll_desinen);
	});
}

// nebestebim paspaudimu
function removeSlideClicks() {
	$$('.rodykle1 img').each(function (el) {
	    $(el).stopObserving('click', scroll_kairen);
	});
	$$('.rodykle2 img').each(function (el) {
	    $(el).stopObserving('click', scroll_desinen);
	});
}

// nuejus nuo elemento
function onBluras(el, tekstas) {
	if($F(el).blank()) {
		el.value=tekstas;
	}
}

// uzejus ant elemento
function onFocusas(el, tekstas) {
	if (el.value == tekstas) {
		el.value = '';
	}
}

/*
 * LYGIAVIMAS
*/

// lygiuojam vertikaliai
function valign(id, min, per_daug) {
	var x = (getWindowHeight() - $(id).getHeight() + per_daug) / 2;
	if(x > 0) {
		if(x < min) {
			$(id).setStyle({top:min+'px'});
			valign_user(min);
		} else {
			$(id).setStyle({top:x+'px'});
			valign_user(x);
		}
	}
}

function valign_user(top) {
	var t = (top - 50) > 0 ? (top - 50) : 0;
	$('user_info').setStyle({top:t+'px'});
}

// grazinamas matomos dalies aukstis
function getWindowHeight() {
    var windowHeight = 0;
    if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    } else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        } else {
            if (document.body && document.body.clientHeight) {
                windowHeight = document.body.clientHeight;
            }
        }
    }
    return windowHeight;
}

// grazinamas matomos dalies aukstis
function getWindowWidth() {
    var windowWidth = 0;
    if (typeof(window.innerWidth) == 'number') {
        windowWidth = window.innerWidth;
    } else {
        if (document.documentElement && document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            if (document.body && document.body.clientWidth) {
                windowWidth = document.body.clientWidth;
            }
        }
    }
    return windowWidth;
}

// apskaiciuojamas plotis
function getWidth() {
	var plotis = 300;
	var dydis = $$('div.item').size();
	return (300+30)*dydis;
}

// nustatomas plotis
function setWidth(id, plotis) {
	$(id).setStyle({width:plotis+"px"})
}

/*
 * SCROLL
*/

function scroll_desinen() {
	scroll_uzdelsimas(18, 55, 1);
}

function scroll_kairen() {
	scroll_uzdelsimas(-18, 55, 1);
}

function scroll_uzdelsimas(atstumas, kartai, uzdelsimas) {
	if(kartai > 0) {
		window.scrollBy(atstumas, 0);
		var delay = function() { scroll_uzdelsimas(atstumas, kartai-1, uzdelsimas); };
		setTimeout(delay, uzdelsimas);
	}
}

/*
 * SARASAS
*/
var animuoti = true;
var sugryzimas = 0;
function setAnimuoti(reiksme) {
	animuoti = reiksme;
}

// parodoma/paslepiama vidine byla
function toggle_vidinis(blokas_id, preke_id, lang_id) {
	var bid = 'blokas_' + blokas_id;
	var vid = 'blokas_' + blokas_id + '_vidinis';

	if (animuoti) { // jei galima animuoti
		setAnimuoti(false);
		// jei jau matomas - paslepiam
		if($(vid).visible()) {
			var new_width = $('container').getWidth() - 565;
			
			new Effect.Fade(vid, { duration: 1.0 });
			new Effect.Morph(bid, { style: 'width:300px',  duration: 1.0, queue: 'end' });
			new Effect.Morph('container', { style: 'width:'+ new_width +'px',  duration: 0.2, queue: 'end' });
			addSlideClicks();
			$(bid + '_pagrindinis').removeClassName('open');
			
			// sugrazinti i buvusia pozicija
			centruoti2.delay(3,bid);
			
		} else {
			// ikeliam prekes info
			new Ajax.Updater(vid, '/ajax/vidinis.tpl', {
				method: 'post',
				evalScripts:true,
				parameters: {	pid: preke_id, lang_id: lang_id, blokas_id: blokas_id }
			});
			
			var new_width = $('container').getWidth() + 565;
			$(bid + '_pagrindinis').addClassName('open');
			
			new Effect.Morph('container', { style: 'width:'+ new_width + 'px',  duration: 0.2 });
			new Effect.Morph(bid, { style: 'width:865px',  duration: 1.0, queue: 'end' });
			new Effect.Appear(vid, { duration: 1.0, queue: 'end' });
			removeSlideClicks();
			
			// centruojam
			centruoti.delay(2,bid);
		}
		setAnimuoti.delay(3,true);
	}
	//return false;
}

// centruojam atverta preke horizontaliai
function centruoti(bid) {
	var ekrano_plotis = getWindowWidth();
	var bloko_plotis = 865;
	var nuotolis = $(bid).viewportOffset();
	
	var kaire = Math.ceil((ekrano_plotis - bloko_plotis) / 2);
	var atstumas = nuotolis[0] - kaire;
	sugryzimas = 0-atstumas; // kiek poto reikes sugryzti
	scroll_uzdelsimas(Math.round(atstumas/20), 20, 1);
}

// sugrazinam i ta pacia pozicija
function centruoti2(bid) {
	var ekrano_plotis = getWindowWidth();
	var bloko_plotis = 865;
	var nuotolis = $(bid).viewportOffset();
	
	var kaire = Math.ceil((ekrano_plotis - bloko_plotis) / 2);
	var atstumas = nuotolis[0] - kaire;

	if (atstumas > 20) {// jei didelis nukrypimas, t.y. paskutinems prekems
		var gryz = sugryzimas + atstumas;
		scroll_uzdelsimas(Math.round(gryz/20), 20, 1);
	} else {
		scroll_uzdelsimas(Math.round(sugryzimas/20), 20, 1);
	}
}

// keiciam foto priklausomai nuo prekes, spalvos ir eiles nr
function changeFoto(blokas_id, lang_id, preke_id, eil_nr) {
	spalva_id = $F('preke_' + preke_id + '_spalvos');
	
	// ikeliam prekes info
	new Ajax.Updater('vidinis_'+ blokas_id +'_kaire', '/ajax/vidinis_foto.tpl', {
		method: 'post',
		parameters: {	blokas_id: blokas_id, pid: preke_id, spalva_id: spalva_id, eil_nr: eil_nr, lang_id: lang_id }
	});
	
	return false;
}

function zoom(blokas_id, foto_id) {
	blokas = 'zoom_'+ blokas_id;
	blokas_close = 'zoom_'+ blokas_id + '_close';
	new Ajax.Updater(blokas, '/ajax/vidinis_zoom.tpl', {
		method: 'post',
		parameters: {	blokas_id: blokas_id, foto_id:foto_id  },
		evalScripts:true
	});
	
	new Effect.Appear(blokas, { duration: 0.8, queue: 'end' });
	new Effect.Appear(blokas_close, { duration: 0.2, queue: 'end' });
	return false;
}

function zoom_close(blokas_id) {
	blokas = 'zoom_'+ blokas_id;
	blokas_close = 'zoom_'+ blokas_id + '_close';
	new Effect.Fade(blokas_close, { duration: 0.2, queue: 'end' });
	new Effect.Fade(blokas, { duration: 0.5, queue: 'end' });
	return false;
}


/*
 * FORMOS
*/

function uzpildytiForma(id) {
	values = gautiPradinesReiksmes();
	$(id).getElements().each(function(el) {
		
		// default reiksme
		if(el.value == '') 	el.value = values[el.id];
		
		// po ivedimo reiksme
		$(el).observe('blur', function() {
			if(el.value == '') 	el.value = values[el.id];
		});
		
		// pries ivedima reiksme
		$(el).observe('focus', function() {
			if(el.value == values[el.id]) el.value = '';
		});

	});
}

function valytiForma(id) {
	values = gautiPradinesReiksmes();
	$(id).getElements().each(function(el) {
		el.value = values[el.id];
	});
	return false;
}

// tikrinam el pasta
function check_email(str) {
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	(filter.test(str)) ? testresults=true : testresults=false;
	return (testresults)
}

// tikrinam raides
function check_string(str) {
	var filter=/^[a-zA-ZĄČĘĖĮŠŲŪŽąčęėįšųūž ]+$/;
	(filter.test(str)) ? testresults=true : testresults=false;
	return (testresults)
}

// tikrinam telefona
function check_phone(str) {
	var filter=/[0-9+ ()]{6}/;
	(filter.test(str)) ? testresults=true : testresults=false;
	return (testresults)
}

// uzklausos forma
function process_uzklausa() {
	values = gautiPradinesReiksmes();
	mess = gautiKlaidas();
	forma = $('forma_uzklausa');
	klaida = $('klaida_uzklausa');
	geri = true;

	forma.getElements().each(function(el) {
		if($F(el).blank() || $F(el) == values[el.id]) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'uzklausa_telefonas' && check_phone($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'uzklausa_elpastas' && check_email($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		}  else if(el.id == 'uzklausa_lygtis' && $F(el) != sk) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		}
	});
	
	if (geri) {
		forma.hide();
		klaida.update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater(klaida.id, '/ajax/uzklausa.tpl', {	method: 'post', parameters: forma.serialize() });
	}
	
	return false;
}

// registracijos forma
function process_registracija() {
	values = gautiPradinesReiksmes();
	mess = gautiKlaidas();
	forma = $('forma_registracija');
	klaida = $('klaida_registracija');
	geri = true;

	forma.getElements().each(function(el) {
		if($F(el).blank() || $F(el) == values[el.id]) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'registracija_telefonas' && check_phone($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'registracija_elpastas' && check_email($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'registracija_slaptazodis2') {
			if($F('registracija_slaptazodis2') != $F('registracija_slaptazodis1')) {
				klaida.update(mess[el.id]);
				el.focus();
				geri = false;
				throw $break;
			}
		} else if(el.id == 'uzklausa_lygtis' && $F(el) != sk) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		}
	});
	
	if (geri) {
		forma.hide();
		klaida.update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater(klaida.id, '/ajax/registracija.tpl', {	method: 'post', parameters: forma.serialize() });
	}
	
	return false;
}

// redagavimo forma
function process_redagavimas() {
	values = gautiPradinesReiksmes();
	mess = gautiKlaidas();
	forma = $('forma_redagavimas');
	klaida = $('klaida_redagavimas');
	geri = true;

	forma.getElements().each(function(el) {
		if($F(el).blank()) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'red_telefonas' && check_phone($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'red_elpastas' && check_email($F(el)) == false) {
			klaida.update(mess[el.id]);
			el.focus();
			geri = false;
			throw $break;
		}
	});
	
	if (geri) {
		forma.hide();
		klaida.update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater(klaida.id, '/ajax/registracija_update.tpl', {	method: 'post', parameters: forma.serialize() });
	}
	
	return false;
}

// registracijos forma
function process_login() {
	values = gautiPradinesReiksmes();
	mess = gautiKlaidas();
	forma = $('forma_login');
	klaida = $('user_info');
	geri = true;

	forma.getElements().each(function(el) {
		el.removeClassName('red');
		if($F(el).blank() || $F(el) == values[el.id]) {
			el.addClassName('red');
			el.focus();
			geri = false;
			throw $break;
		} else if(el.id == 'login_name' && check_email($F(el)) == false) {
			el.addClassName('red');
			el.focus();
			geri = false;
			throw $break;
		}
	});
	
	if (geri) {
		new Ajax.Updater(klaida.id, '/ajax/login.tpl', {	method: 'post', parameters: forma.serialize(), evalScripts:true });
		//klaida.update('<img src="/images/ajax-loader.gif" alt="" />');
	}
	
	return false;
}

// registracijos forma
function process_logout() {
	new Ajax.Updater('user_info', '/ajax/logout.tpl', {	method: 'post', evalScripts:true });
	return false;
}

// redagavimo forma
function process_priminimas() {
	forma = $('forma_priminimas');
	new Ajax.Updater(forma.id, '/ajax/priminimas.tpl', {	method: 'post', parameters: forma.serialize() });
	return false;
}


// POPUP
function popup(id,lang_id){
	var plotis = 500;
	var aukstis = 460;
	var kaire = window.screen.width / 2 - plotis / 2;
	var virsus = window.screen.height / 2 - aukstis / 2;
	newwindow = window.open('/komentarai.tpl?id=' + id + '&lang_id=' + lang_id, 'komplektas', "height=" + aukstis + ",width=" + plotis + ",left=" + kaire + ",top=" + virsus + ',location=0,menubar=0,scrollbars=1,status=0,toolbar=0,resizable=0');
	if (window.focus) { newwindow.focus() }
		return false;
}

function addVote(pid, balsas) {
	$('reit_' + pid).update('<img src="/images/ajax-loader.gif" alt="" />');
	new Ajax.Updater('reit_' + pid, '/ajax/reitingai.tpl', {	method: 'post', parameters:{preke_id:pid, balsas:balsas} , evalScripts:true });
	return false;
}

/*
 * KREPSELIS
*/

function updateCartView() {
	new Ajax.Updater('item_krepselis', '/turinys/krepselis.tpl', {
		method: 'post',
		evalScripts: true
	});
}

function addToCart(pid) {
	var spalva = $('preke_'+pid+'_spalvos') ? $F('preke_'+pid+'_spalvos') : 0;
	$('user_info').update('<img src="/images/ajax-loader.gif" alt="" />');
	new Ajax.Updater('user_info', '/ajax/cart_add.tpl', {
		method: 'post',
		evalScripts: true,
		parameters: {
			pid : pid,
			spid : spalva,
			kiekis : $F('krepselis_' + pid)
		}
	});
	//$('krepselis_' + pid).value='vnt.';
	return false;
}

function updateCart(pid) {
	$('user_info').update('<img src="/images/ajax-loader.gif" alt="" />');
	new Ajax.Updater('user_info', '/ajax/cart_update.tpl', {
		method: 'post',
		evalScripts: true,
		parameters: {
			pid : pid,
			kiekis : $F('krepselis_' + pid)
		}
	});
	updateCartView.delay(0.3); // nes Opera neatnaujino
	return false;
}

function delFromCart(pid, klausimas) {
	if(confirm(klausimas)) {
		$('user_info').update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater('user_info', '/ajax/cart_delete.tpl', {
			method: 'post',
			evalScripts: true,
			parameters: {
				pid : pid
			}
		});
		updateCartView.delay(0.3); // nes Opera neatnaujino
	}
	return false;
}

function delFromCartAll(klausimas) {
	if(confirm(klausimas)) {
		$('user_info').update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater('user_info', '/ajax/cart_delete_all.tpl', {
			method: 'post',
			evalScripts: true
		});
		updateCartView.delay(0.3); // nes Opera neatnaujino
	}
	return false;
}

function buyForPoint(pid, klausimas, atsakymas) {
	if(confirm(klausimas)) {
		var spalva = $('preke_'+pid+'_spalvos') ? $F('preke_'+pid+'_spalvos') : 0;
		$('user_info').update('<img src="/images/ajax-loader.gif" alt="" />');
		new Ajax.Updater('user_info', '/ajax/cart_point.tpl', {
			method: 'post',
			evalScripts: true,
			parameters: {
				pid : pid,
				spid: spalva,
				atsakymas: atsakymas
			}
		});
		$('btn_'+pid).hide();
	}
	return false;
}


/*
LYGTIS
*/

var sk = -1;

function generateLygtis() {
	var val1 = Math.ceil(Math.random()*9);
	var val2 = Math.ceil(Math.random()*9);
	
	sk = val1 + val2;
	$('lygtis').update(val1 + ' + ' + val2 + ' = ');
}

function toggle_atsakymas(id) {
	$$('.atsakymas').each(function (el) {
	    el.hide();
	});
	$('ats' + id).show();
	return false;
}

/*
dovanu kodas
*/

function tikrinti_koda() {
	var kodas = $F('dovanu_kodas');
	//if(kodas.length == 10) {
		new Ajax.Updater('dovanu_kodas_tekstas', '/ajax/cart_dovanu_kodas.tpl', {
			method: 'post',
			parameters: {	kodas : kodas	}
		});
	//}
}

function toggle_check(pasirinktas_elementas) {
	var forma = $('forma_krepselis');
	//var pasirinktas_elementas = forma.getInputs('checkbox').find(function(checkbox) { return checkbox.checked; });
	
	if(pasirinktas_elementas.checked) {
		forma.getInputs('checkbox').each(function(el) {
			if(el.id == pasirinktas_elementas.id) {//console.log(el.id);
				el.checked = true;
			} else {
				el.checked = false;
			}
		});
	} else {
		pasirinktas_elementas.checked = false;
	}
	
	if($('check1').checked) {
		$('check1_box').show();
	} else {
		$('check1_box').hide();
	}

}

function updateShip() {
	var adresas = $F('ship_adresas').empty() ? $('ship_adresas').defaultValue : $F('ship_adresas');
	var miestas = $F('ship_miestas').empty() ? $('ship_miestas').defaultValue : $F('ship_miestas');
	var salis = $F('ship_salis').empty() ? $('ship_salis').defaultValue : $F('ship_salis');
	var url = '/ajax/updateShip.tpl?adresas=' + encodeURIComponent(adresas) + '&miestas=' + encodeURIComponent(miestas) + '&salis=' + encodeURIComponent(salis);
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: updateCartView
	});

}


