var WindowObjectReference = null; // global variable

function otworz_okno(strUrl, strWindowName, width, height)
{
var strWindowName = 'Zdjecie';
  if(WindowObjectReference == null || WindowObjectReference.closed)
  {
    WindowObjectReference = window.open(strUrl, strWindowName,
           "resizable=yes,scrollbars=yes,status=yes,width="+width+",height="+height);
  }
  else
  {
    WindowObjectReference.focus();
  };
}

function poprawne_haslo(h1, h2) {
	var t1 = document.getElementById(h1).value;
	var t2 = document.getElementById(h2).value;
	if(t1!=t2) {
		alert('Wpisane hasła na zgadzają się!');
		return false;
	}
	return true;
}

	function clickclear(thisfield, defaulttext) {
		if (thisfield.value == defaulttext) {
			thisfield.value = "";
		}
	}

	function clickrecall(thisfield, defaulttext) {
		if (thisfield.value == "") {
			thisfield.value = defaulttext;
		}
	}

	var faktura_imie = "";
	var faktura_nazwisko = "";
	var faktura_ulica = "";
	var faktura_mieszkanie = "";
	var faktura_dom = "";
	var faktura_kod = "";
	var faktura_miejscowosc = "";

	function InitSaveVariables(form) {
	//faktura_imie = form.faktura_imie.value;
	//faktura_nazwisko = form.faktura_nazwisko.value;
	faktura_ulica = form.faktura_ulica.value;
	faktura_mieszkanie = form.faktura_mieszkanie.value;
	faktura_dom = form.faktura_dom.value;
	faktura_kod = form.faktura_kod.value;
	faktura_miejscowosc = form.miejscowosc.value;
	}

	function ShipToBillPerson(form) {
	if (form.copy.checked) {
	InitSaveVariables(form);
	//form.faktura_imie.value = form.imie.value;
	//form.faktura_nazwisko.value = form.nazwisko.value;
	form.faktura_ulica.value = form.ulica.value;
	form.faktura_mieszkanie.value = form.mieszkanie.value;
	form.faktura_dom.value = form.dom.value;
	form.faktura_kod.value = form.kod.value;
	form.faktura_miejscowosc.value = form.miejscowosc.value;

	} else {
	//form.faktura_imie.value = faktura_imie;
	//form.faktura_nazwisko.value = faktura_nazwisko;
	form.faktura_ulica.value = faktura_ulica;
	form.faktura_mieszkanie.value = faktura_mieszkanie;
	form.faktura_dom.value = faktura_dom;
	form.faktura_kod.value = faktura_kod;
	form.faktura_miejscowosc.value = faktura_miejscowosc;
	}
	}
	//  End -->

	/* The following function creates an XMLHttpRequest object... */

function createRequestObject(){
	var request_o; //declare the variable to hold the object.
	var browser = navigator.appName; //find the browser name
	if(browser == "Microsoft Internet Explorer"){
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	return request_o; //return the object
}

/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject();

/* Function called to get the product categories list */
function getProducts(rozmiar, prod, targetDiv, szczegoly){
	/* Create the request. The first argument to the open function is the method (POST/GET),
		and the second argument is the url...
		document contains references to all items on the page
		We can reference document.form_category_select.select_category_select and we will
		be referencing the dropdown list. The selectedIndex property will give us the
		index of the selected item.
	*/



	http.open('get', '/parametry/?rozmiar='
			+rozmiar+'&prod='+prod+'&targetDiv='+targetDiv+'&szczegoly='+szczegoly);

	/* Define a function to call once a response has been received. This will be our
		handleProductCategories function that we define below. */
		var obj = document.getElementById(targetDiv);
	http.onreadystatechange = function() {
		if(http.readyState == 4){ //Finished loading the response
			/* We have got the response from the server-side script,
				let's see just what it was. using the responseText property of
				the XMLHttpRequest object. */
			var response = http.responseText;
			/* And now we want to change the product_categories <div> content.
				we do this using an ability to get/change the content of a page element
				that we can find: innerHTML. */
			obj.innerHTML = response;
		}
	}
	/* Send the data. We use something other than null when we are sending using the POST
		method. */
	http.send(null);
}

function spraw() {
	if (document.f1.s1.value==0) {
		alert("Wybierz sposób platnosci");
		return false;
	} else {
		return true;
	}
}



function openRequestedPopup3()
{
 WindowObjectReference = window.open("przypominacz.php",
       "DescriptiveWindowName",
       "resizable=yes,scrollbars=yes,status=yes,width=400,height=300");
}


function ajax_pobierz_kolory(id, miejsce) {
	var rozmiar = document.getElementById('rozmiary_id_'+id).value;
	if (rozmiar == 0) {
		document.getElementById('kolory_div_id_'+id).innerHTML = '';
		document.getElementById('submit_button_id_'+id).onclick = kolorICena;
		return;
	}
	//var id = document.getElementById('produkty_id').value;

	var strURL = '/ext/rozmiary_kolory/kolory/'+id+'/'+rozmiar+'/'+miejsce;

	http.open('POST', strURL);

	http.setRequestHeader("Method", "POST " + strURL + " HTTP/1.1");
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
		if(http.readyState == 4){ //Finished loading the response
			var response = http.responseText;
			document.getElementById('kolory_div_id_'+id).innerHTML = response;
			if (document.getElementById('submit_button_id_'+id).onclick.length > 0) { //!!!!!!!!!!!!!!!!!!!!!!!!!!
				document.getElementById('submit_button_id_'+id).onclick = function () {
					document.getElementById('koszyk_id_'+id).submit();
				}
			}
		}
	}

	http.send(null);
}
function ajax_poinformuj_o_porownaniu(wlacz_wylacz) {
	if (wlacz_wylacz) {
		var strURL = '/ext/porownywarka/zaczynaj';
	} else {
		var strURL = '/ext/porownywarka/wylacz';
	}

	http.open('POST', strURL);

	http.setRequestHeader("Method", "POST " + strURL + " HTTP/1.1");
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
		if(http.readyState == 4){ //Finished loading the response
			var i = 0;
			porownywarka_stan = !porownywarka_stan;

			if (wlacz_wylacz) {
				document.getElementById('porownywarka_ed_id').innerHTML = 'Wyłącz porównywarke';
				document.getElementById('porownywarka_wyswietl_button_id').style.visibility = 'visible';
				document.getElementById('porownywarka_wyswietl_button_id').style.height = 'auto';
			} else {
				document.getElementById('porownywarka_ed_id').innerHTML = 'Porównaj produkty';
				document.getElementById('porownywarka_wyswietl_button_id').style.visibility = 'hidden';
				document.getElementById('porownywarka_wyswietl_button_id').style.height = '0px';
			}

			while (true) {
				var ckb = document.getElementById('prownanie_id_'+i++);

				if (ckb!=null) {
					if (wlacz_wylacz) {
						ckb.style.visibility = 'visible';
						ckb.style.height = 'auto';
					} else {
						ckb.style.visibility = 'hidden';
						document.getElementById('ckb_porownanie_id_'+(i-1)).checked = false;
						ckb.style.height = '0px';
						zaznaczono = 0;
					}
				} else {
					break;
				}
			}
		}
	}

	http.send(null);
}

function ajax_dodaj_do_porownania(id, nr) {
	var strURL = '/ext/porownywarka/dodaj/'+id;
	var komunikat = komunikat;

	http.open('POST', strURL);

	http.setRequestHeader("Method", "POST " + strURL + " HTTP/1.1");
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
		if(http.readyState == 4){
			document.getElementById('komonikat_prownanie_id_'+nr).innerHTML = 'porównaj';
			document.getElementById('ckb_porownanie_id_'+nr).disabled = false;
		}
	}

	http.send(null);
}

function kolorICena() {
	alert("Najpierw wybierz rozmiar i kolor");
	return true;
}

function round_number (num, dec)
{ // low-level numeric format with upward rounding at 5+
 var cDec = '.'; // decimal point symbol
 if (!(dec >= 0 && dec <= 9))
  dec = 2;
 if (isNaN (num) || num == '')
 { // zero values are returned in proper decimal format
  var sdec = "";
  for (var i = 0; i < dec; i++)
   sdec += '0';
  return "0" + (sdec != "" ? cDec + sdec : "");
 }
 var snum = new String (num);
 var arr_num = snum.split (cDec);
 var neg = '';
 var nullify = 0;
 dec_a = arr_num.length > 1 ? arr_num[1].length : 0;
 if (dec_a <= dec)
 { // fill decimal places with trailing zeros if necessary
  if (!dec_a)
   arr_num[1] = "";
  for (var i = 0; i < dec - dec_a; i++)
   arr_num[1] += '0';
  dec_a = dec;
 }
 // total decimal places in value before rounding and formatting
 dec_i = dec_a;
 dec_a -= dec;
 if (arr_num[0].charAt(0) == '-')
 { // preserve negative symbol, remove from value (calculations)
  neg = '-';
  arr_num[0] = arr_num[0].substring (1, arr_num[0].length);
 }
 if (!parseInt (arr_num[0])) // case when whole value is 0
 { // nullify a zero whole value for correct decimal point placement
  arr_num[0] = "1"; // 0 whole # would not preserve amount in calc.
  nullify = 1; // flag to remove greatest 1 portion from whole #
 }
 var whole = parseInt (arr_num[0] * Math.pow (10, arr_num[1].length));
 // remove leading zeros
 for (i = 0; i < arr_num[1].length; i++)
  if (arr_num[1].charAt (i) != '0')
   break;
 if (arr_num[1].length == i) // decimal portion blank or all zeros
  return (neg + arr_num[0] + (arr_num[1] != "" ? (cDec + arr_num[1]) : ""));
 whole += parseInt (arr_num[1].substring (i, arr_num[1].length));
 if (arr_num[1].length != dec)
 { // round number affecting appropriate cluster of decimal places
  var diff = "";
  var str = new String (whole);
  for (i = dec_a; i > 0; i--)
   diff += str.charAt (str.length - i);
  diff = Math.pow (10, dec_a) - parseInt (diff);
  whole += ((diff <= 5 * Math.pow (10, dec_a - 1)) ? diff : 0);
 }
 str = new String (whole);
 var str_f = "";
 var j = 0;
 var k = 0;
 if (nullify)
 {
  arr_num[0] = "0"; // remove 1 from greatest decimal place (restoration)
  str = (parseInt (str.charAt(0)) - 1) + str.substring (1, str.length);
 }
 else // re-assign whole numeric portion from entire numeric string value
  arr_num[0] = str.substring (0, str.length - dec_i);
 for (i = 0; i < str.length; i++)
 { // combine portions of decimal number (whole, fraction, sign)
  if (k - 1 > dec)
   break; // fraction termination case
  if (j == arr_num[0].length)
  {
   if (!j)
    str_f += 0;
   str_f += (dec != 0 ? cDec : ''); // insert decimal point
   --i; // backtrack one character
   k++; // signal fraction count
  }
  else // assign character by character
   str_f += str.charAt (i);
  j++;
  if (k) // fractional counter increment
   k++;
 }
 return neg + str_f;
}

function stat() {
	var OSName="Unknown OS";
	if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
	if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
	if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
	if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

	var strURL = '/ext/licznik/'+screen.width+'/'+screen.height+'/'+OSName;
	http.open('POST', strURL);

	http.setRequestHeader("Method", "GET " + strURL + " HTTP/1.1");
	http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
	//	var response = http.responseText;
	}

	http.send(null);
}

//------------------------------------------------------------------------------

function $(id) {
	return document.getElementById(id);
}

function getElementsByTagAndClassValue(tag, value) {
	var tags = document.getElementsByTagName(tag);
	var result = new Array();

	for(var i=0; i<tags.length; i++) {
		var A = tags[i].attributes;

		if (tags[i].className.indexOf(value) != -1) {
			result.push(tags[i]);
		}
	}

	return result;
}


var formsData = new Array();
var frmIdx=0;
var loadingHeight = 140;
function cartInitialize() {
	var body = document.body;

	var loadingDiv = document.createElement('div');
	loadingDiv.id = 'loading_id';
	loadingDiv.style.zIndex = 222;
	loadingDiv.innerHTML = '<br><br><center><br><br><img src="/view/img/ajax-loader.gif"><br>Dodaje do koszyka. Proszę czekać.<br></center>';
	loadingDiv.style.visibility = 'hidden';

	var maskDiv = document.createElement('div');
	maskDiv.id = 'mask_id';
	maskDiv.style.position = 'absolute';
	maskDiv.style.top = '0px';
	maskDiv.style.left = '0px';
	maskDiv.style.display = 'block';
	maskDiv.style.zIndex = 220;
	maskDiv.style.filter = 'alpha(opacity=80)';
	maskDiv.style.MozOpacity='.80';
	maskDiv.style.opacity='.80';
	maskDiv.style.backgroundColor = '#333';
	//maskDiv.style = 'position:absolute;top:0px;left:0px;display:none;z-index:200;filter:alpha(opacity=80);-moz-opacity:.80;opacity:.80;';
	body.appendChild(loadingDiv);
	body.appendChild(maskDiv);

	var carts = getElementsByTagAndClassValue('form', 'koszyczek');

	for (var frmIdx=0; frmIdx<carts.length; frmIdx++) {
		var obj = carts[frmIdx];

		var idElementObj = document.createElement('input');
		idElementObj.name = 'idx_element';
		idElementObj.value = frmIdx;
		idElementObj.type = 'hidden';

		formsData[frmIdx] = new Array();
		formsData[frmIdx]['formObj'] = obj;
		formsData[frmIdx]['formObj'].appendChild(idElementObj);
		formsData[frmIdx]['objCena'] = obj.cena;
		formsData[frmIdx]['objIlosc'] = obj.ilosc;
		formsData[frmIdx]['prodIdObj'] = obj.produkty_id;
		formsData[frmIdx]['submitObj'] = obj.do_kosza;

		formsData[frmIdx]['rozmiarObj'] = null;
		formsData[frmIdx]['kolorObj'] = null;

		if (obj.rozmiar) {
			formsData[frmIdx]['rozmiarObj'] = obj.rozmiar;
		}

		if (obj.rozmiar) {
			formsData[frmIdx]['kolorObj'] = obj.kolor;
		}

		formsData[frmIdx]['submitObj'].onclick = function () {
			var arrayPageSize = getPageSize();


			var maskDiv = $('mask_id');
			maskDiv.style.width = '100%';
			maskDiv.style.height = arrayPageSize[1]+'px';
			maskDiv.style.display = 'block';

			var loadingDiv = $('loading_id');
			loadingDiv.style.marginTop = ((-(loadingHeight/2))+scrollTop())+'px';
			loadingDiv.style.visibility = 'visible';

			var i = lookingByName(this.parentNode, 'idx_element').value;//this.parentNode.idx_element.value
			//alert(formsData[frmIdx]['objCena']);
			if (formsData[i] && (this.rozmiar != null || this.kolor != null)) {
				if (!this.rozmiar.selectedIndex || this.rozmiar.selectedIndex == 0) {
					alert("Najpierw wybierz rozmiar i kolor!");
					return false;
				} else if (this.kolor && (!this.kolor.selectedIndex || this.kolor.selectedIndex == 0)) {
					alert("Najpierw wybierz rozmiar i kolor!");
					return false;
				}
			}

			var objCena = formsData[i]['objCena'];
			var objIlosc = formsData[i]['objIlosc'];
			var objProdId = formsData[i]['prodIdObj'];
			var objRozmiar = this.parentNode.rozmiar;
			var objKolor = this.parentNode.kolor;


			var strURL = '/ext/do_koszyka/'+readCookie('sesja')+'/'+objProdId.value+'/'+objIlosc.value+'/'+objCena.value;
			if (this.parentNode.rozmiar) {
				strURL += '/'+objRozmiar.options[objRozmiar.selectedIndex].value;
				if (this.parentNode.kolor) {
					strURL += '/'+objKolor.options[objKolor.selectedIndex].value;
				}
			}
			http.open('POST', strURL);

			http.setRequestHeader("Method", "POST " + strURL + " HTTP/1.1");
			http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

			http.onreadystatechange = function() {
				if(http.readyState == 4){
					var response = http.responseText;
					//alert(response);
					var dane = eval('(' + response + ')');
					//alert(dane['liczba_produktow']);
					loadingDiv.innerHTML = dane['html'];
					$('liczb_prod_w_koszyku_id').innerHTML = dane['liczba_produktow'];
					$('suma_koszyka_id').innerHTML = dane['suma'];
				}
			}

			http.send(null);


			return false;
		}
	}
}

function closeInfo() {
	var maskDiv = $('mask_id');
	maskDiv.style.display = 'none';

	var loadingDiv = $('loading_id');
	loadingDiv.style.visibility = 'hidden';
	loadingDiv.innerHTML = '<center><img src="/view/img/ajax-loader.gif"><br>Dodaje do koszyka. Proszę czekać.<br></center>';
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

function scrollLeft() {
	return filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function scrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function lookingByName(obj, name) {
	for (var ei = 0; ei < obj.elements.length; ei++) {
		if (obj.elements[ei].name && obj.elements[ei].name == name)
		return obj.elements[ei];
	}
}