var activeKat=false;
var kontrahent_id=0;

function showJSWarnings(jData){
	document.getElementById(jData.id).innerHTML=jData.separator+jData.text;
}

function makePOSTRequest(url, parameters) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
      	// set type accordingly to anticipated content type
         //http_request.overrideMimeType('text/xml');
         http_request.overrideMimeType('text/html');
      }
   } else if (window.ActiveXObject) { // IE
      try {
         http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e) {}
      }
   }
   if (!http_request) {
      alert('Cannot create XMLHTTP instance');
      return false;
   }

   http_request.onreadystatechange = alertContents;
   http_request.open('POST', url, true);
   http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   http_request.setRequestHeader("Content-length", parameters.length);
   http_request.setRequestHeader("Connection", "close");
   http_request.send(parameters);
}

function alertContents() {
   if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        //alert(http_request.responseText);
        //result = http_request.responseText;

      } else {
         alert('There was a problem with the request.');
      }
   }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

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 eraseCookie(name) {
	createCookie(name,"",-1);
}

function jsonGrabe(req) {
	request = req;
	// Create a new script object
	// (implementation of this class is in /js/jsr_class.js)
	aObj = new JSONscriptRequest(request);
	// Build the script tag
	aObj.buildScriptTag();
	// Execute (add) the script tag
	aObj.addScriptTag();
}

function kategoria(id){
	var katId="kat"+id;
	document.getElementById(katId).style.display='block';
	if(activeKat && activeKat!=katId){
		document.getElementById(activeKat).style.display='none';
	}
	activeKat=katId;
}

function testCookie(){
	createCookie("cookietest",1,1);
	var testCookie = readCookie("cookietest");
	if(testCookie!=null)
		return "ok";
	else
		return "brak";
}

function dodajDoSchowka(Id){
	var cookie = testCookie();
	if(cookie=="ok"){
		if(!kontrahent_id){
			kontrahent_id=readCookie("kontrahent_id");
		}
		jsonGrabe('includes/ajax.schowek.php?produkt_id='+Id+'&kontrahent_id='+kontrahent_id);
	}else{
		alert("Aby uzywac schowka musisz miec wlaczona obsluge plikow Cookie w swojej przegladarce.");
	}
}

function pobierzSchowek(kontrahent_id){
	if(kontrahent_id){
		jsonGrabe('includes/ajax.pokazschowek.php?kontrahent_id='+kontrahent_id);
	}else{
		document.getElementById("schowek").innerHTML="Brak produktów w twoim Schowku";
	}
}

function schowekSzczegoly(Id){
	var divId = "opis"+Id;
	var hrId = "hr"+Id;
	var imgId = "img"+Id;
	var open = new Image();
	open.src = "gfx/open.gif";
	var close = new Image();
	close.src = "gfx/close.gif";

	if(document.getElementById(divId).style.display=="block"){
		document.getElementById(divId).style.display="none";
		document.getElementById(hrId).style.display="block";
		document[imgId].src=open.src;
	}else{
		document.getElementById(divId).style.display="block";
		document.getElementById(hrId).style.display="none";
		document[imgId].src=close.src;
	}
}

function pokazSchowek(jData){
	document.getElementById(jData.id).innerHTML=jData.text;
	createWindow('Moj Schowek', 400, 'white', 1, 0, 240, 75);
}

function zapiszOpis(val,Id){
	var content = val.value; 

	var parameters="value="+encodeURIComponent(content)+"&id="+Id;
	makePOSTRequest("includes/ajax.zapiszschowek.php", parameters);
}

function zapiszKontrahenta(field){
	if(!kontrahent_id){
		kontrahent_id=readCookie("kontrahent_id");
	}
	var value=document.getElementById(field).value;
	jsonGrabe('includes/ajax.zapiszkontrahent.php?kontrahent_id='+kontrahent_id+'&value='+value+'&field='+field);
}

function zapiszUwagi(field){
	var value=document.getElementById(field).value;

	var parameters="value="+encodeURIComponent(value)+"&kontrahent_id="+kontrahent_id+"&field="+field;
	makePOSTRequest("includes/ajax.zapiszkontrahent.php", parameters);
}

function usunZeSchowka(Id){
	if(!kontrahent_id){
		kontrahent_id=readCookie("kontrahent_id");
	}
	jsonGrabe('includes/ajax.usunzeschowka.php?id='+Id+'&kontrahent_id='+kontrahent_id);
}

function wyslijZapytanie(knhId){
	var alert1=false;
	var alert2="";
	var typ = document.getElementById("typ").value;
	var frima=document.getElementById("kontrahent_nazwa").value+document.getElementById("kontrahent_osoba").value;
	var kontakt=document.getElementById("kontrahent_tel").value;
	var to_owner=document.getElementById("to_owner").checked;
	var kontakt_mail=document.getElementById("kontrahent_email").value;
	var email=validateEmail(document.getElementById("kontrahent_email").value);
	if(frima=="" || !frima){
		alert1=true;
		alert2="Pole: Nazwa Firmy lub Osoba do Kontaktów musi być wypełnione";
	}

	if((kontakt=="" || !kontakt) && (kontakt_mail=="" || !kontakt_mail)){
		alert1=true;
		alert2+=" Pole: Adres Email lub Numer telefonu musi być wypełnione";
	}

	if(kontakt_mail!="" && !email){
		alert1=true;
		alert2+=" Wpisany adres email ma nieprawidłową strukturę";
	}
	
	if(to_owner && ((kontakt_mail=="" || !kontakt_mail) || !email)){
		alert1=true;
		alert2+=" Musisz prawidłowo wypełnić pole email";
	}

	if(!alert1){
		var req='includes/ajax.wyslijzapytanie.php?toowner='+to_owner+'&kontrahent_id='+kontrahent_id+'&typ='+typ;
//		alert(req);
		jsonGrabe(req);
		alert("Zapytanie zostało wysłane");
	}else{
		alert(alert2);
	}
}

function validateEmail(email)
{
// a very simple email validation checking. 
// you can add more complex email checking if it helps 
    var splitted = email.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null) 
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
return false;
}

function szukaj(host){
	location.href=host+"?q="+document.getElementById("szukaj").value;
}

function checkKey(evt,host){
	var key = (typeof evt.which != "undefined") ? evt.which : event.keyCode;
	if(key==13)
		location.href=host+"?q="+document.getElementById("szukaj").value;
}

function getBack(){
	window.history.back();
}