// Ostatnia modyfikacja: 2008.03.23 14:13

//var DHTML; //zmienna potrzebna do zapytania XmlHttpRequest
var separator=GetAsciiChar(27);

function GetAsciiChar(charcode) {
	var a=charcode . toString(16);
	if (a.length==1)
		a='0'+a;
	return unescape('%'+a);
}


function AddToCart(songNo, remove) {
	
	if (!HttpAddToCart(songNo, remove)) {
		alert("Przepraszamy, ale Twoja przeglądarka nie obsługuje dodawania piosenek do koszyka bez przeładowania strony. Prosimy o poinformowanie o takiej sytuacji administratora tej strony (milimetr88@gmail.com lub marcinbor@o2.pl).\n\nZalecamy zainstalowanie jednej z nowszych wersji przeglądarki Firefox, Opera lub Internet Explorer.");
		return true; //oznacza dla JS, że link ma być przetworzony normalnie
	}	
	else
		return false;
}

//var Host=null;
var temp=document.location+"";
var Host=temp.substring(0, temp.lastIndexOf('/'));

if (Host.substring(Host.length-1)=='/')
	Host=Host.substring(0, Host.length-1);


function HttpAddToCart(songNo, remove) {
	
	
	var URL=Host+"/koszyk.php?action=dodaj&produkt="+songNo+"&toUTF";
	if (remove!=null)
		URL+="&usun";
	// alert(URL);	
	var XMLObj;

	if (!(XMLObj=GetHttpRequest()))
		return false;
		
	XMLObj.onreadystatechange = function () {
		
		if (XMLObj.readyState!=4) return;

		try {
						
			if (XMLObj.status!=200 && XMLObj.status!=304) {
				alert("NIE UDAŁO SIĘ dodać do koszyka (problem z połączeniem - błąd "+XMLObj.status+")");
				return; 
			}

		}
		catch(e) {
			var key="status";
			if (XMLObj.key == undefined)
				alert("Nie udało się dodać piosenki do koszyka!");
			else {
				alert("Wystąpił błąd: "+e.name+", "+e.message);
			}

			return;
		}

		XMLHandlerAddToCart(XMLObj, songNo);

	}
	
	XMLObj.open("GET", URL);
	XMLObj.send("");
	
	return true; //true oznacza, że stworzono obiekt HttpRequest, a nie że udało się dodać :)
}


function handleErr(msg,url,l)
{
	txt="There was an error on this page.\n\n";
	txt+="Error: " + msg + "\n";
	txt+="URL: " + url + "\n";
	txt+="Line: " + l + "\n\n";
	txt+="Click OK to continue.\n\n";
	alert(txt);
	return true;
}


function XMLHandlerAddToCart(XMLObj, songNo) {
	// alert(XMLObj.responseText);

	var response=XMLObj.responseText;
	var arr=response.split(separator);

	add=(arr[0]=='1');
	songNo=arr[1];
	title=arr[2];
	price=arr[3];
	zobacz=arr[4];
	akt_cena=arr[5];
	
	//pric=arr[3];
	// alert(arr[0]);
	// alert(add);
	var Cart=new getObj('div_koszyk'); //gets the cell containing the cart
	//Cart.obj.innerHTML=xml;//XMLObj.responseText; //paste HTML code returned from server

	if (add) { //remove==null) { //if it's adding, not removing, hide link and cart button, show cart icon
		AddDiv(Cart.obj, 'div_koszyk_'+songNo, title);
		HideMult('link'+songNo);
		HideMult('koszyk'+songNo);
		HideMult('koszykB'+songNo, 'inline');
	}
	else {
		DeleteDiv(Cart.obj, 'div_koszyk_'+songNo);
		//alert("a");
// the third parameter - silent mode: do not show message box with an error message if there is no such object
		HideMult('link'+songNo, 'inline'); 
		HideMult('koszyk'+songNo, 'inline');
		HideMult('koszykB'+songNo, null);
		var obj_row=new getObj('row_'+songNo, false);
		if (obj_row.obj!=null)
			window.location.reload(true);
		//Hide('row_'+songNo, null, 1);
	}

	
	var koszyk_cena=new getObj('koszyk_cena');
	koszyk_cena.obj.innerHTML=price; //+" zł";
	
	var koszyk_zobacz=new getObj('koszyk_zobacz');
	koszyk_zobacz.obj.innerHTML=zobacz; //+" zł";
	
	
	
	if (akt_cena!='') { //zmień wszystkie ceny piosenek na stronie na odpowiednio niższe
			
		var elem_cena=getElementsByStyleClass('cena');
		var cena_podst;
		var arr_cena;
		if (elem_cena!=null) {
			for (var e=0;e<elem_cena.length; e++) {
				arr_cena=elem_cena[e].id.split('_');
				cena_podst=arr_cena[2];
				if (cena_podst!=null)
					elem_cena[e].innerHTML=format(akt_cena/100*cena_podst/100);
					//elem_cena[e].innerHTML=akt_cena/100*cena_podst/100+' PLN';
			}
		}
	}
	
}


function format(num) {
	num = eval(num);
	num *= 100;
	num = Math.round(num)/100;

	if (num - Math.floor(num) == 0) {
		num = num + ",00";
	} else {
		string = num.toString();
		parts = string.split(".");
		cents = parts[1];
			if (cents.length == 1) {
				parts[1]=parts[1]+'0';
				//num = num + "0";
				}
		num=parts[0]+','+parts[1];
	}

	num = num + ' PLN';
	return num;
}

//based on http://www.thescripts.com/forum/thread170283.html and http://www.faqts.com/knowledge_base/view.phtml/aid/2193/fid/128
function getElementsByStyleClass (className) {
	var all;
	if (document.all)
		all=document.all;
	else {
		var docBody = document.body || document.documentElement;
		if (!docBody || !docBody.getElementsByTagName) return;
		all=docBody.getElementsByTagName('*');
	}
	
	var elements = new Array();
	for (var e = 0; e < all.length; e++)
		if (all[e].className == className)
			elements[elements.length] = all[e];
	return elements;
}


function AddDiv(parent, id, value) {
	var oldobj=new getObj(id, false);
	if (oldobj.obj!=null)
		return;

	var newdiv=document.createElement('div');
	newdiv.setAttribute('id', id);
	newdiv.id=id;
	newdiv.setAttribute('class', 'koszyk');
	newdiv.setAttribute('className', 'koszyk');
	newdiv.innerHTML=value;
	parent.appendChild(newdiv);

}


function DeleteDiv(parent, id) {
	var obj=new getObj(id, false);
	if (obj.obj!=null)
		parent.removeChild(obj.obj);
	// else
		// alert("Brak obiektu: "+id);
}


function Hide(objId, hide, silent) {

	if (silent==null || !silent)
		silent=false;

	var Obj=new getObj(objId, !silent);
	
	if (Obj.obj!=null) {
		if (hide==null)
			Obj.style.display='none';
		else {
			switch(hide) {
			case 'block':
			case 'inline':
				Obj.style.display=hide; break;
			default:
				Obj.style.display='inline'; break;	
			}
		}
	}
	else
		if (!silent)
			alert("Błąd - brak obiektu: '"+objId+"'!\n\nZgłoś ten błąd administratorowi strony!");

}

function HideMult(objId, hide) {

	
	var Obj;
	var counter=1;
	do {
		
		Obj=new getObj(objId+'_'+counter, 0);
		
		if (Obj.obj!=null) {
			if (hide==null)
				Obj.style.display='none';
			else {
				switch(hide) {
				case 'block':
				case 'inline':
					Obj.style.display=hide; break;
				default:
					Obj.style.display='inline'; break;	
				}
			}
		}
		// else
			// if (!silent)
				// alert("Błąd - brak obiektu: '"+objId+"'!\n\nZgłoś ten błąd administratorowi strony!");
		counter++;
	} while(Obj.obj!=null);
}


function GetHttpRequest() {
	
	var req = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest && !(window.ActiveXObject))
	{
    	try
		{
			req = new XMLHttpRequest();
        }
		catch(e)
		{
			req = false;
        }
    
	// branch for IE/Windows ActiveX version
    }
	else
		if(window.ActiveXObject) {
	       	try
			{
	        	req = new ActiveXObject("Msxml2.XMLHTTP");
	      	}
			catch(e)
			{
	        	try
				{
	          		req = new ActiveXObject("Microsoft.XMLHTTP");
	        	}
				catch(e)
				{
	          		req = false;
	        	}
			}
		}
	
	return req;
}



//default for alertIfNull is TRUE
function getObj(id, alertIfNull)
{
		
	if (alertIfNull==null || alertIfNull)
		alertIfNull=true;
	else
		alertIfNull=false;
		
		
	if (document.getElementById)
	{	
	  	this.obj = document.getElementById(id);
		if (this.obj!=null)
			this.style = document.getElementById(id).style;
	}
	else if (document.all)
	{
		this.obj = document.all[id];
		if (this.obj!=null)
			this.style = document.all[id].style;
	}
	else if (document.layers)
	{
		this.obj = document.layers[id];
		if (this.obj!=null)
			this.style = document.layers[id];
	}
	else {
		if (alertIfNull)
			alert("Błšd przy próbie pobrania elementu "+id);
		this.obj=null;
	}
  
	if (this.obj==null && alertIfNull)
		alert("NIE MA TAKIEGO ELEMENTU: "+id);

}


function LoadPage(sitename) {
	
	if (!HttpLoadPage(sitename)) {
		alert("Przepraszamy, ale Twoja przeglądarka nie obsługuje odświeżania strony w tle. Prosimy o poinformowanie o takiej sytuacji administratora tej strony (milimetr88@gmail.com lub marcinbor@o2.pl).\n\nZalecamy zainstalować jedną z nowszych wersji przeglądarki Firefox, Opery lub Internet Explorer.");
		return true; //oznacza dla JS, że link ma być przetworzony normalnie
	}	
	else
		return false;
}

function HttpLoadPage(sitename) {

	//var Host=GetHost(location.href);
	// var Host=document.location.hostname;
	// alert(document.location); //http://localhost/dvdkaraoke/?show=piosenki
	// alert(document.location.hash);
	// alert(document.location.host); //localhost
	// alert(document.location.hostname);//localhost
	// alert(document.location.href);//http://localhost/dvdkaraoke/?show=piosenki
	// alert(document.location.pathname);// /dvdkaraoke/
	// alert(document.location.port); // empty??
	// alert(document.location.protocol);//http:
	// alert(document.location.search); //?show=piosenki
	// alert(document.location.replace); // function replace() { [native code] }
	// alert(document.location.assign); // function assign() { [native code] }
	// alert(document.location.reload); // function reload() { [native code] }
	//var URL="http://karafun.pl/koszyk.php?action=dodaj&produkt="+songNo+"&toUTF";
	//var URL="http://"+Host+"/index2.php?show="+sitename+"&toUTF";
	
	//var arr=document.location.pathname.split('/');
	//arr[arr.length-1]='';
	
	// if (Host.substring(Host.length-1)=='/')
		// Host=Host.substring(0, Host.length-1);
		
	// alert(Host);
	
	//var URL=document.location.protocol+'//'+document.location.hostname+arr.join('/')+"index2.php?show="+sitename+"&toUTF";
	var URL=Host +"/index2.php?show="+sitename+"&toUTF";
	
//alert(URL);
	var XMLObj;

	if (!(XMLObj=GetHttpRequest()))
		return false;
	
	XMLObj.onreadystatechange = function () {
		if (XMLObj.readyState!=4) 
			return;
		
		try {
			if (XMLObj.status!=200 && XMLObj.status!=304) {
				alert("NIE UDAŁO SIĘ załadować strony (problem z połączeniem, status: "+XMLObj.status+")");
				return; 
			}
		}
		catch(e) {
			alert("Wyjątek! "+e+":"+e.description);
		}
		
		XMLHandlerLoadPage(XMLObj, sitename);
	}
	
//	XMLObj.onerror = handleErr;
	
	// function() {
		// alert("Wystąpił błąd przy dodawaniu do koszyka:");
		// alert("Wystąpił błąd przy dodawaniu do koszyka: "+XMLObj.status+", "+XMLObj.responseText);
	// }
		
	//alert(URL);
	XMLObj.open("GET", URL);
	XMLObj.send("");
	
	return true; //true oznacza, że stworzono obiekt HttpRequest, a nie że udało się załadować nową stronę :)
	
}

function XMLHandlerLoadPage(XMLObj, sitename) {
	
	var obj = new getObj('podstrona');
	obj.obj.innerHTML=XMLObj.responseText;
	
}

