/* Zażółć gęślą jaźń */
var ile_promocji = 0;
var ferszlus = 0;
var form_time;
var final_time;
var proper_params = new Array('czesci_marki_id','czesci_model','czesci_rocznik','czesci_grupy_id','czesci_rodzaj');

function depolonize_fonts(znaki) {
	var pl_fonts = new Array 		(/ą/g, /ć/g, /ę/g, /ł/g, /ń/g, /ó/g, /ś/g, /ź/g, /ż/g, /Ą/g, /Ć/g, /Ę/g, /Ł/g, /Ń/g, /Ó/g, /Ś/g, /Ź/g, /Ż/g);
	var de_pl_fonts = new Array	('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
	for (i=0; i<=pl_fonts.length; i++) {
		znaki = znaki.replace(pl_fonts[i], de_pl_fonts[i]);
	}
	return znaki;
}

var Url = {
 	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 		for (var n = 0; n < string.length; n++) {
 			var c = string.charCodeAt(n);
 			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 		}
 		return utftext;
	},
 	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 		while ( i < utftext.length ) {
 			c = utftext.charCodeAt(i);
 			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 		}
 		return string;
	}
}

/* wooohooo IE fixing ! */

function fixthecrap() {
	//use browser sniffing to determine if IE or Opera (ugly, but required)
	var isOpera, isIE = false;
	if(typeof(window.opera) != 'undefined'){isOpera = true;}
	if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true;}

	//fix both IE and Opera (adjust when they implement this method properly)
	if(isOpera || isIE){
		document.nativeGetElementById = document.getElementById;
		//redefine it!
		document.getElementById = function(id){
			var elem = document.nativeGetElementById(id);
			if(elem){
				//verify it is a valid match!
				if(elem.attributes['id'] && elem.attributes['id'].value == id){
					//valid match!
					return elem;
				} else {
					//not a valid match!
					//the non-standard, document.all array has keys for all name'd, and id'd elements
					//start at one, because we know the first match, is wrong!
					for(var i=1;i<document.all[id].length;i++){
						if(document.all[id][i].attributes['id'] && document.all[id][i].attributes['id'].value == id){
							return document.all[id][i];
						}
					}
				}
			}
			return null;
		};
	}
}

function pole_blur_and_focus(pole, tekst) {
pole_focus(pole, tekst);
pole_blur(pole, tekst);
}

function pole_focus(pole, tekst) {
	document.getElementById(pole).onfocus = function() {return pole_focus2(pole, tekst);};
}

function pole_focus2(pole, tekst) {
	if (document.getElementById(pole).value==tekst) document.getElementById(pole).value='';
}

function pole_blur(pole, tekst) {
	document.getElementById(pole).onblur = function() {return pole_blur2(pole, tekst);};
}

function pole_blur2(pole, tekst) {
	if (document.getElementById(pole).value=='') document.getElementById(pole).value=tekst;
}

function formowanie() {
	var pola = {
	'email':'Wpisz adres e-mail...',
	'czesci_tekst':'Wpisz nazwę części...',
	'marka':'Wpisz nazwę marki...',
	'model':'Wpisz nazwę modelu...',
	'rok':'Wpisz rocznik...',
	'silnik':'Wpisz rodzaj silnika...',
	'przebieg':'Wpisz przebieg...',
	'lokalizacja':'Wpisz adres postoju pojazdu...',
	'wyposazenie':'Opis wyposażenia...',
	'uszkodzenia':'Opis uszkodzeń...',
	'cena':'Wpisz proponowaną cenę...',
	'imie-nazwisko':'Wpisz imię i nazwisko...',
	'telefon':'Wpisz numer telefonu...',
	};
	for (var pole in pola) {
		try {pole_blur_and_focus(pole, pola[pole]);}
		catch (excostam) {	}
	}
	try {document.getElementById("sortuj").onchange = function() {return idzdo('sortuj', escape(this.value));};}
	catch (excostam) {	}
	try {document.getElementById("stronicowanie").onchange = function() {return idzdo('stronicowanie', escape(this.value));};}
	catch (excostam) {	}
	try {document.getElementById("producent").onchange = function() {return idzdo('producent', escape(this.value));};}
	catch (excostam) {	}
	try {document.getElementById("link-zapytanie").onclick = pops;}
	catch (excostam) {	}
}

var parser = new DOMImplementation();
advAJAX.setDefaultParameters({
  onSuccess : function(obj) {
		document.getElementById(obj.tag).innerHTML = '';
		var domDoc = parser.loadXML(obj.responseText);
		var docRoot = domDoc.getDocumentElement();
		var ileOptions = docRoot.getElementsByTagName("option").length;
		var liczajka;
		var selectie;
		var optie;
		var tekscik;
		var wartoscik;
		var disabledzik;
		var selectedzik;
		var idzik;
		for (liczajka=0;liczajka<=ileOptions-1;liczajka=liczajka+1)  {
			try {
				tekscik = docRoot.getElementsByTagName("option").item(liczajka).getFirstChild();
				wartoscik = docRoot.getElementsByTagName("option").item(liczajka).getAttribute("value");
				disabledzik = docRoot.getElementsByTagName("option").item(liczajka).getAttribute("disabled");
				selectedzik = docRoot.getElementsByTagName("option").item(liczajka).getAttribute("selected");
				idzik = docRoot.getElementsByTagName("option").item(liczajka).getAttribute("id");
			}
			catch (zzz) {
				
			}
			selectie = document.getElementById(obj.tag);
			optie = document.createElement('option');
			optie.value = wartoscik;
			optie.text = tekscik;
//			optie.id = idzik;
//			optie.disabled = disabledzik;
			optie.selected = selectedzik;
			selectie.options.add(optie);
		}
		ferszlus = ferszlus-1;
		if(obj.tag == "czesci_model") {
			document.getElementById("czesci_model").disabled = false;
			if (ileOptions == 1) {
				document.getElementById("czesci_model").disabled = true;
			}
		}
		else if(obj.tag == "czesci_rodzaj") {
			document.getElementById("czesci_rodzaj").disabled = false;
			if (ileOptions == 1) {
				document.getElementById("czesci_rodzaj").disabled = true;
			}
		}
	}
});

// funkcja daje disabled pozycjom w formularzu wyszukiwania które powinny być nieklikalne, bo są puste
function make_disabled() {
	var listy = new Array('czesci_marki_id','czesci_model','czesci_rocznik','czesci_grupy_id','czesci_rodzaj');
	var lista;
	var reg = /\([0-9]*\)/;
	for (licznik=0; licznik < listy.length; licznik++) {
		lista = document.getElementById(listy[licznik]);
		for (licznik2=0; licznik2 < lista.options.length; licznik2++) {
			if (!reg.test(lista.options[licznik2].text) && lista.options[licznik2].value != "") {
				lista.options[licznik2].disabled="disabled";
			}
		}
	}
}

function doaja(tabela, zapytanie) {
	advAJAX.get({ url: "libs/czesci.lib.php?strona=ajax&query=dodatki&return=select&dla="+tabela+"&"+zapytanie, tag: tabela });
}

function final_timer() {
	document.getElementById('middlesearch').style.visibility="visible";
	document.getElementById('middlesearchload').style.visibility="hidden";
	ferszlus = 0;
	clearTimeout(final_time);
}

function check_form() {
	if(ferszlus < 1) { document.getElementById('middlesearch').style.visibility="visible";
	document.getElementById('middlesearchload').style.visibility="hidden";
	clearTimeout(form_time);
	clearTimeout(final_time);
	}
	else { form_time=setTimeout("check_form()",1000); }
}

// funkcja wywolywana przez onchange event w polach formularza wyszukiwania czesci, jako parametr przyjmuje id wywolujacego - ajaxem zmienia pozostale pola
function reload_search_form(asker) {
	var query = '';
	var remembered_select = new Array();
	
	// machniom
	document.getElementById('middlesearchload').style.visibility="visible";
	document.getElementById('middlesearch').style.visibility="hidden";
	form_time=setTimeout("check_form()",1000);
	final_time=setTimeout("final_timer()",6000)
	
	// sanitarium
	if(asker=='czesci_marki_id') {
		document.getElementById('czesci_model').options.selectedIndex = 0;
	}
	if(asker=='czesci_grupy_id') {
		document.getElementById('czesci_rodzaj').options.selectedIndex = 0;
	}
	
	// budujemy query
	for (liczaj=0;liczaj<=proper_params.length-1;liczaj=liczaj+1) {
		query = query+proper_params[liczaj]+"="+document.getElementById(proper_params[liczaj]).value+"&";
	}
	if(document.getElementById('czesci_tekst').value != 'Wpisz nazwę części...') {
		query = query+'czesci_tekst='+document.getElementById('czesci_tekst').value;
	}
	
	// zapamietujemy ustawione wartosci
	for (liczaj=0;liczaj<=proper_params.length-1;liczaj=liczaj+1) {
		remembered_select[proper_params[liczaj]] = document.getElementById(proper_params[liczaj]).value;
	}
	
	// wywolujemy kilka razy robola od pobrania i sparsowania
	ferszlus = ferszlus+1;
	doaja('czesci_marki_id',query);
	ferszlus = ferszlus+1;
	doaja('czesci_model',query);
	ferszlus = ferszlus+1;
	doaja('czesci_rocznik',query);
	ferszlus = ferszlus+1;
	doaja('czesci_grupy_id',query);
	ferszlus = ferszlus+1;
	doaja('czesci_rodzaj',query);
}

function zalad() {
	for (liczaj=0;liczaj<=proper_params.length-1;liczaj=liczaj+1) {
		document.getElementById(proper_params[liczaj]).onchange = function() {return reload_search_form(this.id);}
	}
}

function addLoadEvent(func) {
	var oldOnload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldOnload();
			func();
		}
	}
}

function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() {return this.keyValuePairs;}
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
			return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() {return this.keyValuePairs.length;}
}

function queryString(key) {
	var page = new PageQuery(document.location.search);
	return unescape(page.getValue(key));
}

function usun_ikonki() {
var divyy = document.body.getElementsByTagName('div');
	for(i=0; i < divyy.length; i++) {
		if (divyy[i].className=='promoinfo')	{
			ile_promocji++;
		}
	}
}

function breed_to_breath(breed, przewijanie) {
	if (typeof breed == "undefined") {
		breed = 1;
  }
	aktywny_obrazek(breed);
	if (typeof przewijanie == "undefined") {
		przewijanie = 1;
  }
	if(przewijanie != 1) {
		clearTimeout(zegarek);
	}
	var divy = document.body.getElementsByTagName('div');
	var licznik = 0;
	for(i=0; i < divy.length; i++) {
		if (divy[i].className=='promoinfo')	{
			licznik++;
			divy[i].setAttribute('style', 'display: none;');
			if(licznik == breed) {
				divy[i].setAttribute('style', 'display: block;');
				if(breed >= ile_promocji) {
					breed=0;
				}
				oko = breed+1;
				if(przewijanie == 1) {
					zegarek=setTimeout("breed_to_breath(oko, true)",3000);
				}
			}
		}
	}
}

function aktywny_obrazek(co) {
	lynky = document.body.getElementsByTagName('a');
	for(z=0; z < lynky.length; z++) {
		if (lynky[z].className=='promo_link')	{
			var off = document.createElement("img");
			off.setAttribute('class', 'promo_link');
			off.setAttribute('src', 'Grafikanew/zmieniarka_off.png');
			off.setAttribute('rel', lynky[z].getAttribute('rel'));
			lynky[z].removeChild(lynky[z].firstChild);
			lynky[z].appendChild(off);
		}
	}
	for(z=0; z < lynky.length; z++) {
		if ((lynky[z].className=='promo_link') && (lynky[z].getAttribute('rel') == co))	{
			var on = document.createElement("img");
			on.setAttribute('class', 'promo_link');
			on.setAttribute('src', 'Grafikanew/zmieniarka_on.png');
			on.setAttribute('rel', lynky[z].getAttribute('rel'));
			lynky[z].removeChild(lynky[z].firstChild);
			lynky[z].appendChild(on);
		}
	}
dopromo();
}

function wylacz_promo() {
	zz = this.getAttribute('rel');
	breed_to_breath(zz, 2);
	return false;
}

function dopromo() {
var linki = document.body.getElementsByTagName('a');
	for(i=0; i < linki.length; i++) {
		if (linki[i].className=='promo_link')	{
			linki[i].onclick = wylacz_promo
		}
	}
}

function txt_promo() {
	var linki = document.body.getElementsByTagName('a');
	for(i=0; i < linki.length; i++) {
		if (linki[i].className=='promo_link_txt')	{
			linki[i].onclick = wylacz_promo
		}
	}
}

function jarjar() {
		var testoleo = this.href;
		var winopts = "dependent=no,toolbar=no,resizable=yes,scrollbars=no,menubar=no,status=no,location=yes,width=790px,height=622px";
		var win = window.open('','_blank',winopts);
		var doc = win.document;
		doc.open('text/html;charset=utf-8');
		doc.writeln('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">');
		doc.writeln('<html xmlns="http://www.w3.org/1999/xhtml">');
		doc.writeln('<head><title>mamauto.pl - części samochodowe</title>');
		doc.writeln('<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />');
		doc.writeln('<meta http-equiv="imagetoolbar" content="false" />');
		doc.writeln('<style>');
		doc.writeln('html, body {padding: 0;margin: 0;}');
		doc.writeln('</style>');
		doc.writeln('</head>');
		doc.writeln('<body>');
		doc.writeln('<p style="margin: 0px;"><img id="popup" src="'+testoleo+'" alt="Zdjęcie"/></p>');
		doc.writeln('</body>');
		doc.writeln('</html>');
		doc.close();
return false;
}

function pops() {
	var linkeo = this.href;
	var winopts = "dependent=no,toolbar=no,resizable=yes,scrollbars=no,menubar=no,status=no,location=yes,width=410px,height=650px";
	var win = window.open(linkeo,'_blank',winopts);
	return false;
}

function dopu() {
var linki = document.body.getElementsByTagName('a');
	for(i=0; i < linki.length; i++) {
		if (linki[i].className=='image_large' || linki[i].className=='image_popup')	{
			linki[i].onclick = jarjar
		}
	}
}

function iefyform() {
	var mail = 'mailto:'+document.getElementById('e_mail_mamauto').value;
	if (document.getElementById('form-kasacja')) {
		try {document.getElementById('form-kasacja').onsubmit = function() {return iefyform_send();};}
		catch (excostam) {	}
	}
	else return false;
}

function iefyform_send() {
	var mail = 'mailto:'+document.getElementById('e_mail_mamauto').value;
	/* formularz kasacji */
	var forkas = {'marka' : 'Marka samochodu',
	'model' : 'Model samochodu',
	'nadwozie' : 'Rodzaj nadwozia',
	'rok' : 'Rok produkcji',
	'silnik' : 'Silnik',
	'paliwo' : 'Rodzaj paliwa',
	'skrzynia' : 'Skrzynia biegow',
	'przebieg' : 'Przebieg (w tys. km)',
	'lokalizacja' : 'Lokalizacja pojazdu',
	'wyposazenie' : 'Opis wyposazenia',
	'uszkodzenia' : 'Opis uszkodzen',
	'cena' : 'Proponowana cena',
	'imie-nazwisko' : 'Imie i nazwisko',
	'telefon' : 'Numer telefonu',
	'email' : 'Adres e-mail'
	};
	if (document.getElementById('form-kasacja')) {
		mail = mail+"?subject="+Url.encode("Samochod do zlomowania")+"&body=";
		for (var pole in forkas) {
			mail = mail+Url.encode(forkas[pole]+": "+depolonize_fonts(document.getElementById(pole).value)+"\r\n\r\n");
		}

		try {document.getElementById('iehelp').href=mail; document.getElementById('iehelp').click(); return false;}
		catch (excostam) {	}
	}
	else return false;
}

addLoadEvent(fixthecrap);
addLoadEvent(usun_ikonki);
addLoadEvent(dopu);
addLoadEvent(dopromo);
addLoadEvent(txt_promo);
addLoadEvent(breed_to_breath);
addLoadEvent(formowanie);
addLoadEvent(zalad);
addLoadEvent(make_disabled);
/*@cc_on 
addLoadEvent(iefyform);
@*/
