// config section
var XXL_TLD = '.xxlmarket.pl';
// --==--==--==--

function isdefined(variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}


function getNewXMLHttpRequest() {
  var obj;
    try {
      // For Internet Explorer.
      obj = new ActiveXObject('Microsoft.XMLHTTP');
    }
    catch(e) {
      try {
        // Gecko-based browsers, Safari, and Opera.
        obj = new XMLHttpRequest();
        if (obj.overrideMimeType) {
            obj.overrideMimeType('text/html');
        };
      }
      catch (e) {
        // Browser supports Javascript but not XMLHttpRequest.
        obj = false;
      }
    }
    return obj;
}

function prepareXMLHttpRequest(elArr,paramDod){
	if( !paramDod ){ paramDod='';}
	for (var i=0; i<elArr.length; i++) {
		var vdata="jsAction="+elArr[i]+paramDod;
		getFromXMLHttpRequest(vdata);
	}
}

function getFromXMLHttpRequest(vdata){
    var req = new XMLHttpRequest();           
    req.open('POST', "/", true);
    if (req.overrideMimeType) req.overrideMimeType('text/html');
    req.setRequestHeader('X-Referer', document.location);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.onreadystatechange = function (aEvt) {
      if (req.readyState == 4) {
         if(req.status == 200){
          if( req.responseText==null ){
						 //					
          }else{
            retstr = req.responseText;
            if ( retstr != '' ){
							var my_regexp = /^(\d+)\$(\w+)/;
							var param = my_regexp.exec(retstr);
							if( param){								
								switch(param[1]) {
									case '0'://innerHTML
										if(obj=$(param[2])){
											var str_length = param[1].length + param[2].length + 2;//plus dwa dolary
											var obj;										
											obj.innerHTML=retstr.substring(str_length);
											runAJAXedJavaScript(param[2]);
										}										
										break;	
								}
							}
            }else{
								//
            }                                        
          }                                                       
        }
      }
    };
    req.send(vdata);
}

//Run AJAXed JavaScript's :)
function runAJAXedJavaScript(oname){
    var tscr = getobject(oname).getElementsByTagName('script');
    for(var i=0;i<tscr.length;i++){
        //alert(tscr[i].text);
        eval(tscr[i].text);
    }
}

function getobject(oname){
  if (document.all && document.all(oname)) {
    return document.all(oname);
  }else{
    if (document.getElementById && document.getElementById(oname)) {
      return document.getElementById(oname);
    };
  };
};

//popup window

var modalTW = null;
var modalTWa = null;

function popupOpenWindow(w,h,url,params){
    if ( !modalTW ){
        modalTW = document.createElement("div");
        modalTW.className = "ofertatwinfo1div";
        modalTW.height = document.body.scrollHeight;
        modalTW.style.height = document.body.scrollHeight+'px';
        modalTW.width = document.body.scrollWidth;
        modalTW.style.width = document.body.scrollWidth+'px';
        document.body.appendChild(modalTW);
        modalTWa = document.createElement("div");
        modalTWa.className = "ofertatwinfo2div";
        modalTWa.width = w;
        modalTWa.id = 'ofertatwinfo2id';
        modalTWa.name = 'ofertatwinfo2id';
        modalTWa.style.width = w+'px';
        modalTWa.height = h;
        modalTWa.style.height = h+'px';
        modalTWa.top=document.body.scrollTop+(window.innerHeight/2)-(h/2);
        modalTWa.style.top=(document.body.scrollTop+(window.innerHeight/2)-(h/2))+'px';
        //modalTWa.onclick = function() { popupCloseWindow() };
        modalTW.appendChild(modalTWa);
        if ( url != '' ){
            sendRequestAndGetInnerHTML(params,url,'ofertatwinfo2id');
        }
    }
}

function popupCloseWindow(){
    if ( modalTW ){
        document.body.removeChild(modalTW);
        modalTW = null;
        modalTWa = null;
    }
}

function popupOnScroll(){
    if ( modalTWa ){
        modalTWa.top=document.body.scrollTop+(window.innerHeight/2)-(modalTWa.height/2);
        modalTWa.style.top=(document.body.scrollTop+(window.innerHeight/2)-(modalTWa.height/2))+'px';
    }
}

function popupOnResize(){
    if ( modalTWa ){
        modalTWa.top=document.body.scrollTop+(window.innerHeight/2)-(modalTWa.height/2);
        modalTWa.style.top=(document.body.scrollTop+(window.innerHeight/2)-(modalTWa.height/2))+'px';
    };
    if ( modalTW ){
        modalTW.height = document.body.scrollHeight;
        modalTW.style.height = document.body.scrollHeight+'px';
        modalTW.width = document.body.scrollWidth;
        modalTW.style.width = document.body.scrollWidth+'px';
    };
};

//
function imswt(aname, asrc){
    aname.src = asrc;
}

//

function ThumbMouseOver(tmo_obj){
    if (document.all && document.all('thmb_img_big')) {
       document.all('thmb_img_big').src = tmo_obj.src;
    }else{
       if (document.getElementById && document.getElementById('thmb_img_big')) {
           document.getElementById('thmb_img_big').src = tmo_obj.src;
       }
   }
}

function ThumbMouseOut(){
    if (document.all && document.all('thmb_img_big')) {
       document.all('thmb_img_big').src = ThmbSrc;
    }else{
       if (document.getElementById && document.getElementById('thmb_img_big')) {
           document.getElementById('thmb_img_big').src = ThmbSrc;
       }
   }
}

function PutThumbToFull(srct){
    if (document.all && document.all('thmb_img_big')) {
       document.all('thmb_img_big').src = loader.src;
       document.all('thmb_img_big').src = srct;
    }else{
       if (document.getElementById && document.getElementById('thmb_img_big')) {
           document.getElementById('thmb_img_big').src = loader.src;
           document.getElementById('thmb_img_big').src = srct;
       }
   }
};

// 000 loading in new window 000

function OpenFullView(tind, srct1){
    var  w = screen.availWidth;
    var  h = screen.availHeight;
    duzezdj = window.open("","oknoz","toolbar=0,left=0,top=0,location=0,directories=0,status=0,menubar=0,resizable=1,dependent=1,hotkeys=0,scrollbars=1,titlebar=0,z-lock=1,width="+w+",height="+h+"");
    duzezdj.resizeTo(w,h);
    duzezdj.document.write("<HEAD>");
    duzezdj.document.write("<TITLE>Wczytuję dane...</TITLE>");
    duzezdj.document.write("</HEAD>");
    duzezdj.document.write("<body bgcolor='#FFFFFF' onload=\"window.location.href='/?zdjeciadet&_g[ind]="+tind+"&_g[zid]="+srct1+"'\">");
    duzezdj.document.write('<font size="2" face="Verdana"><CENTER><BIG><B>Wczytuję dane. Proszę czekać...</B></BIG></CENTER></font></body>');
    duzezdj.focus();
    duzezdj.location.href='/?zdjeciadet&_g[ind]='+tind+'&_g[zid]='+srct1;
};

function OpenFullViewPorow(){
    var  w = screen.availWidth;
    var  h = screen.availHeight;
    duzezdj = window.open("","oknoz","toolbar=0,left=0,top=0,location=0,directories=0,status=0,menubar=0,resizable=1,dependent=1,hotkeys=0,scrollbars=1,titlebar=0,z-lock=1,width="+w+",height="+h+"");
    duzezdj.resizeTo(w,h);
    duzezdj.document.write("<HEAD>");
    duzezdj.document.write("<TITLE>Wczytuję dane...</TITLE>");
    duzezdj.document.write("</HEAD>");
    duzezdj.document.write("<body bgcolor='#FFFFFF' onload=\"window.location.href='/genporw.php'\">");
    duzezdj.document.write('<CENTER><font size="2" face="Verdana"><B>Wczytuję dane. Proszę czekać...</B></font></CENTER></body>');
    duzezdj.focus();
    duzezdj.location.href='/genporw.php';
};

function ttt(a) { alert(a.src); }

function oftw_Corelate(id,ref){
	window.document.location.href = ref+'?corelate=&_g[id]='+id;
}

function sendRequestAndGetResult(srldata,aurl){
    var req = getNewXMLHttpRequest();
    req.open('POST', aurl, false);
    req.setRequestHeader('X-Referer', document.location);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send(srldata);
    return req.responseText;
}

// plik register_user_form zid=1 ->login, zid=2 ->haslo, zid=3 ->detale-zamawiam, zid=4 ->filtr
function gethelp(zid){
    var dname = 'd_help'+zid;
    if ( getobject(dname) ){
        if ( getobject(dname).innerHTML == 'Ładuję...' ){
            switch(zid){
            case '1' : getobject(dname).innerHTML = '<b>Login</b><br><br>Twój login, to unikalna w całym &quot;Systemie XXLmarket&quot; nazwa użytkownika.<br><br>Pamiętaj aby wybrać taki, który łatwo zapamiętasz.<br>Znaki, z których może się składać to litery (bez polskich), cyfry i kropka.<br>'; break;
            case '2' : getobject(dname).innerHTML = '<b>Hasło</b><br><br>Twoje hasło nie powinno być takie samo jak login. Musi zawierać minimum 6 znaków (bez polskich).<br><br>Pamiętaj aby wybrać takie, które łatwo zapamiętasz, a jednocześnie nikt inny nie będzie mógł go odgadnąć.'; break;
            case '3' : getobject(dname).innerHTML = '<b>Zamawiam</b><br><br>Wybierz ofertę i podaj zamawianą ilość, następnie kliknij w [Zamawiam]. '; break;
            case '4' : getobject(dname).innerHTML = '<b>Filtr</b><br><br>Wybierz z dostępnych pól odpowiednie cechy produktów i kliknij [Pokaż].<br>Aby rozpocząć filtrowanie od nowa kliknij [Zeruj].<br><br>Rozpocznij selekcję od pola najistotniejszego dla Ciebie z wszystkich prezentowanych.<br><br>Wybór dostępnej cechy eliminuje z pozostałych pól pozycje niespełniające zadanego warunku.Wyjątkiem jest pole wyboru &quot;Producent&quot; i &quot;Marka&quot;, w których zawartość nie jest ograniczana względem siebie.'; break;

            };
        };
        getobject(dname).style.visibility = 'visible';
    };
};

function closehelp(zid,nadpisac){
    var dname = 'd_help'+zid;
    if ( getobject(dname) ){
        getobject(dname).style.visibility = 'hidden';
        if(nadpisac){
          getobject(dname).innerHTML = 'Ładuję...';
        };
    };
};

function testLogedIn(gdzie){
    var retval;
    retval=sendRequestAndGetResult('is_logged=',XXLMARKET_URL);
    if ( retval!='OK'){
        if ( gdzie=='psg'){
            window.location.href=XXLMARKET_URL+'?psg';
        }else{
            window.location.href=XXLMARKET_URL;
        }
    }
    return true;
}

function testSzukanaFraza(obj){
    if(obj.value=='szukana fraza') obj.value = '';
}

//zaokraglanie fakturowe (pl standard)
function getFakturaRound(aVal){
   if ( aVal!=Math.floor(aVal) ){
       var dxVal = 0;
       var txVal = 0;
       var tVal = Math.floor(aVal*100);
       txVal = tVal/100;
       if ( tVal<0 ) {
            dxVal = -1;
       }else{
            dxVal = 1;
       };
       if ( Math.abs(aVal-txVal)>=0.005 ){
            tVal = tVal+dxVal;
       };
       return tVal/100;
   }else{
       return aVal;
   }
}

function sendByUrl(s,p){
	var redir = '/?'+s;
	var obj;
	for ( var i=0; i<p.length; i++ ){
		obj = getobject(p[i]);
		if ( obj ){
			redir += '&'+p[i]+'='+encodeURIComponent(obj.value);
		}
	}
	window.document.location.href=redir;
}


//dodane przez Marka
var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}

Object.extend = function(destination, source) {
	for (property in source) destination[property] = source[property];
	return destination;
}

function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}

if (!window.Element) var Element = new Object();

Object.extend(Element, {
    css: function(element, style) {
    element = $(element);
        for (var name in style) {
          var value = style[name];
          name = stringCamelize(name);
          element.style[name] = value;
        }
    },
	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},
	hasClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var hasClass = false;
		element.className.split(' ').each(function(cn){
			if (cn == className) hasClass = true;
		});
		return hasClass;
	},
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
   	}
});

function stringCamelize(str) {
    var parts = str.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = str.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
}

function getElementsByClass(searchClass, nodeId, tag){
    var classElements = new Array();
    if (nodeId == null){ node = document;}else{ node=$(nodeId);}
    if (tag == null){ tag = '*';}
    var els = node.getElementsByTagName(tag);
    var pattern = new RegExp("(^|\\\\s)" + searchClass + "(\\\\s|$)");
    for (var i = 0, child; child = els[i]; i++) {
        if ( child.className && pattern.test(child.className)){ classElements.push(child);}
    }
    return classElements;
}

function inArray(arr,key){
	for (var i=0; i<arr.length; i++) {
		if( arr[i]==key ){ return true;}
	}
	return false;
}

function getParentElementByClass(searchClass, o_parent){
	var pattern = new RegExp("(^|\\\\s)" + searchClass + "(\\\\s|$)");
	obj=$(o_parent);
	while( obj ){
		if ( obj.className && pattern.test(obj.className)){ return obj;}
		obj = obj.parentNode;    
	}
	return null; 
}

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}

Array.prototype.removeKey = function (key) {
    for (var i=0;i<this.length;i++){ 
    	if(this[i]==key){
    	    this.splice(i,1);
        }
    }
}

Array.prototype.iterate = function(func){
	for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;

function $c(array){
	var nArray = [];
	for (var i=0;i<array.length;i++) nArray.push(array[i]);
	return nArray;
}

mrkTimex = Class.create();
mrkTimex.prototype =  {
	initialize: function(el, options) {
    this.remain_all=1*60*10;
    this.remain_step=200;
		this.timer = null;
		this.onstep=null;
		this.onstart=null;
		this.onend=null;
		this.dir=1;
	},
	
	step: function() {
		var time  = (new Date).getTime();
		if (time >= this.startTime + this.remain_all) {
			clearInterval (this.timer);
			this.timer = null;
			if( this.onend!=null ){
    	        this.onend();	
	        }
		}else{
    		if( this.onstep!=null ){
    	        this.onstep();	
	        }
		}

	},

	display: function() {
    this.startTime = (new Date).getTime();
		if (this.timer != null) return;
		this.timer = setInterval (this.step.bind(this), this.remain_step);
		if( this.onstart!=null ){
    	    this.onstart();	
	    }
	},

	clearTimer: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
} 

// --- funkcja w zaleznosci od przegladarki ustawia alpha(opacity) albo opacity 
var opera=(navigator.userAgent.indexOf("Opera")>-1);
var ie=(document.all&&!opera);

function setOpacity(id, ile) {
	ile = parseInt(ile);
	if (ie&&!opera) {
		id.style.filter='alpha(opacity='+ile+')';
	} else {
		id.style.opacity=ile/100;				
	}	
}

function obAddEL(ob, evt, evf){
	if (ob.addEventListener){
	  ob.addEventListener(evt, evf, false); 
	} else if (ob.attachEvent){
	  ob.attachEvent('on'+evt, evf);
	}
}


var winScroller = {
	isScrolling: false,
	
	oldCoords: false,
	
	doScroll: function (ev){
		if ( !this.isScrolling ) return true;

		var event = ev||window.event;
		
		if ( !event.pageX && event.button==0 ){
			this.isScrolling = false; return true;
		}
		
		var dx = 0; 
		var dy = 0;
		var coords = new Object();
		
		coords.x = event.clientX;
		coords.y = event.clientY;

		if ( !this.oldCoords ){
			this.oldCoords = coords;
			return true;
		}
		
		dx =this.oldCoords.x-coords.x;
		dy = this.oldCoords.y-coords.y;
		
		window.scrollBy(dx,dy);

		this.oldCoords = coords;
		return true;
	},
	
	startScroll: function(ev){
		this.oldCoords = false;
		this.isScrolling = true; return true;
	},
	
	stopScroll: function(ev){
		this.isScrolling = false; return true;
	},
	
	init: function(){
		obAddEL(document.body, 'mousedown', function(e){ return winScroller.startScroll(e); });
		obAddEL(document.body, 'mouseup', function(e){ return winScroller.stopScroll(e); });
		obAddEL(document.body, 'mousemove', function(e){ return winScroller.doScroll(e); });
	}
};


//obAddEL(window, 'load', function(e){ winScroller.init(); } );


//multi message imp
function ShowMessages(str){    
    var slist1; var slist2; var obj; var wid=''; var loc=''; var typ;
    slist1 = str.split('|::|');
    for ( i=0; i<slist1.length; i++ ){
        slist2 = slist1[i].split('==');
        if ( slist2.length==2 ){
            switch ( slist2[0] ){
                //what to show in window alert
                case 'windowed': wid += slist2[1]; break;
                //where to go
                case 'location': loc = slist2[1]; break;
                //what js run
                case 'javascript': eval(slist2[1]); break;
                //what and where insert those tekst
                default:
                    obj = getobject(slist2[0]);
                    if ( obj ){
                        switch ( String(obj.tagName).toLowerCase() ){
                            //how to treat a input
                            case 'input':
                                typ = obj.getAttribute("type");
                                switch ( typ ){
                                    //checkbox and radio are checked or not
                                    case 'checkbox':
                                    case 'radio':
                                        obj.checked = (slist2[1]=='true');
                                        break;
                                    //image has a src
                                    case 'image': 
                                        obj.src = slist2[1]; 
                                        break;
                                    //rest is valued
                                    default:
                                        obj.value = slist2[1]; 
                                        break;
                                }
                                break;
                            //for selects it must be a value
                            case 'select': obj.value = slist2[1]; break;
                            //default treat as HTML
                            default: obj.innerHTML += slist2[1]; break;
                        }
                    }
                    break;
            }
        }
    }
    if ( wid != '' ){
        alert(wid);
    }
    if ( loc != '' ){
        window.document.location.href=loc;
    }
    return true;
}

function debugView(boxOpen){
    var o;
    if(o = document.getElementById('debug')){
		if (o.style.width == '18px' || boxOpen ) {
			o.style.width = '500px';
			o.style.height = 'auto';
		}else{
			o.style.width = '18px';
			o.style.height = '18px';
		}
    }    
}

function debugWrite(str,do_clear){
    var debug,debug_body;
    if(debug = document.getElementById('debug')){ debug.style.display='block'; alert(45);}
    if(debug_body = document.getElementById('debug_body')){        
        if( do_clear ){ debug_body.innerHTML = '';}
        str = ""+str;
        list = str.split('&');            
        if( list.length==1 ){ 
            debug_body.innerHTML +=  list[0]+'<br>';
        }else{
            for ( i=0; i<list.length; i++ ){  
                debug_body.innerHTML +=  list[i]+'<br>';
            }
        }
				debugView(true);
    }    
}

function debugWriteFromServer(str){
	var debug,debug_body;
  if(debug = document.getElementById('debug')){ 
		debug.style.display='block';
		debugView(true);
		
		if(debug_body = document.getElementById('debug_body')){
      str = ""+str;
      list = str.split('&');
      debug_body.innerHTML = '';
      if( list.length==1 ){ 
      	debug_body.innerHTML +=  list[0]+'<br>';
      }else{
        for ( i=0; i<list.length; i++ ){  
        	debug_body.innerHTML +=  list[i]+'<br>';
        }
      }
  	}
	}   
}

function debugClear(str){
    if(o = document.getElementById('debug_body')){
        o.innerHTML = '';
    }        
}


 

