//-----parametry a ajax--------------------
var TempAjax = "";
var TempAjaxNavBar = "";
var timeoutGiftOn = 0;

var giftViewOld = 1;
var giftViewNew = 2;

var categoryFilterLocationHash;
var bSearchBot;

categoryFilterLocationHash = '';
bSearchBot = 0;


function WorkAni(oX,oY){
    objGet('Work').style.top = (oY + document.documentElement.scrollTop).toString() + "px";
	objGet('Work').style.left = (oX + 20).toString() + "px";
	objGet('Work').style.display = 'block';
	return;
}


/// Drag&Drop System , pouzito z Interval.cz

	var dragobj;
	
	function m_down(event, object)
	{
	
		
		dragobj = object;      
		
		dragobj.style.zIndex = "5";	
		if(!dragobj.style.left) dragobj.style.left = "0px";
		if(!dragobj.style.top) dragobj.style.top = "0px";
			
		// Zapamatuj pozici mysi pri klintuti
		dragobj.clickX = event.clientX;  
		dragobj.clickY = event.clientY;
			
		// Zapamatuj pozici objektu pri klintuti
		dragobj.left = parseInt(dragobj.style.left); 
		dragobj.top = parseInt(dragobj.style.top);


	 	// Zacni sledovat pohyb mysi
    if(IE)
		{	
			document.attachEvent('onmousemove', m_move); 
			document.attachEvent('onmouseup', m_up); 		
		}else{
			document.addEventListener('mousemove', m_move, true);
			document.addEventListener('mouseup', m_up, true); 		
		}

return stopEvent(event);
}


function m_move(event)
{
	// Spocti rozdil mezi puvodni pozici mysi pri stisku a nynejsi pozici a zavolej proceduru objektu pro presun 
	dragobj.ondragdrop(event.clientX-dragobj.clickX, event);
	return stopEvent(event);
}

function m_up(event)
{
	// Ukonci sledovani mysi
	if(IE)
	{
		document.detachEvent('onmousemove', m_move); 	
		document.detachEvent('onmouseup', m_up); 
		if(dragobj.ondragend)dragobj.ondragend(event);
	}else{
		document.removeEventListener('mousemove', m_move, true); 
		document.removeEventListener('mouseup', m_up, true); 
		if(dragobj.ondragend)dragobj.ondragend(event);
	}
	return stopEvent(event);	
}


// Prirad objektu moznost presunu
function startDrag(what)
{
	if(what.style.position!="relative" && what.style.position!="absolute") {what.style.position="relative";}
	what.onmousedown = function(e) {if(e) {event=e;} m_down(event,what);}
	what.drag = true;
}

// Odeber objektu moznost presunu 
function stopDrag(what)
{
	what.onmousedown = null;
	what.drag = 0;
}

// Zastav sireni udalosti
function stopEvent(event)
{
	if(IE) {
		event.cancelBubble = true; return false;
	}else{
		event.stopPropagation(); event.preventDefault(); return false;
	}
}


function FormatCurr(strCurr,intRound){
	var strCurrTemp = strCurr.toString();
	strCurrTemp = strCurrTemp.toString().replace(',-','');
	strCurrTemp = strCurrTemp.toString().replace(' ','');
	strCurrTemp = strCurrTemp.replace(',','.');
	if (intRound == 1) {
//	    if (euro) { 
//					var intCurr = Math.round(parseFloat(strCurrTemp) / 10) * 10; 
//				}
//	    else { 
		var intCurr = Math.round((parseFloat(strCurrTemp) / nItem)) * nItem;	
//		}
	    
	    if(intCurr < nPriceMin){ intCurr = nPriceMin; }
		if(intCurr > nPriceMax){ intCurr = nPriceMax; }
		   
	}else{
		var intCurr = Math.round(parseFloat(strCurrTemp));
	}
	
	strCurrTemp = intCurr.toString() + ''
	
	return strCurrTemp;
}


function ActionHttpRequestName(url, objName){
	if(url == ''){return}
	if (window.ActiveXObject){
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		httpRequest = new XMLHttpRequest();
	}

	httpRequest.open("GET", url, false);
	httpRequest.setRequestHeader("Content-Type", "text/html; charset=utf-8");
	httpRequest.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
	httpRequest.send(null);

	if (httpRequest.readyState == 4){
		if(httpRequest.status == 200){
			var data;

			data = httpRequest.responseText;
			objGet(objName).innerHTML = data;
			opacityGift('CommodityGiftHoldList', 0, 100, 200, 0);	

		}else{
			alert("Chyba pri nacitani stanky"+ httpRequest.status +":"+ httpRequest.statusText);
		}
	}
}

function GetHttpRequest(url){
	var data = '';
	
	if(url == ''){return}
	if (window.ActiveXObject){
		httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		httpRequest = new XMLHttpRequest();
	}

	httpRequest.open("GET", url, false);
	httpRequest.setRequestHeader("Content-Type", "text/html; charset=utf-8");
	httpRequest.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
	httpRequest.send(null);

	if (httpRequest.readyState == 4){
		if(httpRequest.status == 200){

			data = httpRequest.responseText;

		}else{
			alert("Chyba pri nacitani stanky"+ httpRequest.status +":"+ httpRequest.statusText);
		}
	}
	
	return data;
}


function processRequest(){
  if (httpRequest.readyState == 4){
    if(httpRequest.status == 200){
    	var arrData;
    	var boolShow = 0;
    	data = httpRequest.responseText;
	    objGet('BaseContentPage').innerHTML = data;
	    startDrag(objGet('draggerMin'),1);
	    startDrag(objGet('draggerMax'),1);
    }else{
        alert("Chyba pri nacitani stanky"+ httpRequest.status +":"+ httpRequest.statusText);
    }
  }
}


function formatPrice(strPrice){
	var sPrice = strPrice;
	
	if(sPrice.length > 3){
		sPrice = sPrice.substring(0, sPrice.length - 3 ) + ' ' + sPrice.substring(sPrice.length - 3, sPrice.length)
	}
	
	return sPrice;
}

function InitPrice(){
	if(nPriceMinResult == 0) nPriceMinResult = nPriceMin;
	if(nPriceMaxResult == 0) nPriceMaxResult = nPriceMax;
	if(nPriceMinResult >= nPriceMin){
		//Nastavim minimalni cenu
							objGet('TextMin').innerHTML = '' + formatPrice(FormatCurr(nPriceMinResult/fCoef,0)) + ',-';
							objGet('draggerMin').style.left = Math.round((((nPriceMinResult - nPriceMin) / nItemReal)) * nKoeficient) + 'px';
	}
	if(nPriceMaxResult <= nPriceMax && nPriceMaxResult > 0 ){
		//Nastavim minimalni cenu
						objGet('TextMax').innerHTML = '' + formatPrice(FormatCurr(nPriceMaxResult/fCoef,0)) + ',-';
						objGet('draggerMax').style.left = Math.round(ActualMax - (nKoeficient * Math.round((nPriceMax - nPriceMaxResult)/nItemReal))) + 'px';
		
	}
		
			startDrag(objGet('draggerMin'),1);
			startDrag(objGet('draggerMax'),1);
}

var dragDownMin, dragDownMax, dragHoverMin, dragHoverMax
dragDownMin = 0;
dragDownMax = 0;
dragHoverMin = 0;
dragHoverMax = 0;

function DragPriceInit(){
	$('#draggerMin').hover(
		function(){
			dragHoverMin = 1;
			$('#draggerMin').attr('src','/Img/CategoryHeader/drag.png');
		},
		function(){
			dragHoverMin = 0;
			if(dragDownMin == 0){			
				$('#draggerMin').attr('src','/Img/CategoryHeader/dragGray.png');
			}
		}
	);
	
	$('#draggerMin').mousedown(function(){
		dragDownMin = 1;
	});
	
	$('#draggerMin').mouseup(function(){
		dragDownMin = 0;
		if(dragHoverMin == 0){			
			$('#draggerMin').attr('src','/Img/CategoryHeader/dragGray.png');
		}
	});
	
	$('#draggerMax').hover(
		function(){
			dragHoverMax = 1;
			$('#draggerMax').attr('src','/Img/CategoryHeader/drag.png');
		},
		function(){
			dragHoverMax = 0;
			if(dragDownMax == 0){
				$('#draggerMax').attr('src','/Img/CategoryHeader/dragGray.png');
			}
		}
	);
	
	$('#draggerMax').mousedown(function(){
		dragDownMax = 1;
	});
}

function categoryAjax(request, bEmpty){
	var strPageId = ''
	strPageId = $("#PageID").val();
	var waitLoader
	
	if(parseInt(strPageId) > 0){
		waitLoader = $('<div id="categoryWait"><div class="waitContainer"><img src="/Img/CategoryHeader/ajax-loader.gif" alt="Loading ..." /></div></div>')
	}else{
		waitLoader = $('<div id="categoryWait"><div class="waitContainer"><div class="waitBackground"></div><img src="/Img/CategoryHeader/ajax-loader.gif" alt="Loading ..." /></div></div>')	
	}
	if($('#NewInCategory').length > 0){
		waitLoader.css({'height':$('#NewInCategory').offset().top - $('#BaseContentPage').offset().top});
	}else{
		waitLoader.css({'height':$('#PageCopyright').offset().top - $('#BaseContentPage').offset().top});	
	}
	waitLoader.appendTo($('#AdvanceSearchForm'));
	
//	$(document).scrollTop(0);
	
	if (request.length > 0 && request.substring(request.length - 1, 1) != '&'){
		request = request + '&'
	}
	var prodList = $("#prodFormList input[name='prod']:checked");
	var strProdList = ''
	var strStore = ''
	var strPn = ''
	for(var i = 0; i < prodList.length; i++){
		strProdList = strProdList + prodList[i].value + ',';
	}
	
	if (strProdList.length > 0 && strProdList.substring(strProdList.length - 1, 1) == ','){
		strProdList = strProdList.substring(0,strProdList.length - 1);
	}
	if(objGet('CheckStor') != null && objGet('CheckStor').checked == true){
		strStore = '&stock=ok';
	}
	strPn = $("#categorySorter option:selected").val();
	if(strPn == null){strPn = '';}

	
	if(parseInt(strPageId) > 0){
		removeAfterPaging();
	}
	var url = ''
	var queryString = ''
	queryString = request + 'limit=' + $('#priceLimit').val() + '&prod=' + strProdList + '&pn=' + strPn + '&Pg=' + strPageId + strStore;
	url = '/Execute/CategoryGet.asp?' + queryString;
	var myLocation
	myLocation = window.location.href;
	if(myLocation.indexOf(queryString, 0) <= 0 && bEmpty != 1){
		categoryFilterLocationHash = '#' + queryString;
		window.location = '#' + queryString;
	}

//	window.frames['WinSession'].location.replace('/Execute/CategoryGetSession.asp?filter=OK&' + queryString);

	
	$.ajax({ url: url, async: true , success: function(data){
		var arrData = data.split('#####'); 
		$('#categoryList').html(arrData[1]);
		if($('#categoryList #noResult').length > 0){
			categoryNoResultPosition();
			ProdListSet(arrData[4]);
		}
		else{
			ProdListSet(arrData[4]);
			ComodityBoxResize();
			AnimateActionPrice()
		}
		$('.cube').html(arrData[0]);
		var find, strNavBar;
		strNavBar = ReplaceAll(arrData[0], 'onsubmit();"', 'onsubmit();$(document).scrollTop(0);"' );
		find = 'onsubmit();';
		$('#subCat_1 .cube').html(strNavBar);
		$('.numberItem').html(arrData[2]);
		if($('#topSale').length > 0){
		$('#topSale').html(arrData[3]);
		}
		// Jeste povesim na spodni .cube efekty jako na tlacitko
		bottomCubeEfect();
		waitLoader.remove();
	}, error: function(data){
		$('#categoryList').html('<div id="noResult"><p class="fbig" style="line-height: 21px; color: rgb(0, 40, 90);"><span class="fred fbold">Nepodařilo se načíst kategorii.</span><br />Zkuste zaslat požadavek znova a nebo znova <a href="" class="fbold">načtěte stránku</a></p><div></div></div>');
		categoryNoResultPosition();		
		waitLoader.remove();
	}
	});
	
	objGet('PageID').value=0
}

function ReplaceAll(Source,stringToFind,stringToReplace){

  var temp = Source;

    var index = temp.indexOf(stringToFind);

        while(index != -1){

            temp = temp.replace(stringToFind,stringToReplace);

            index = temp.indexOf(stringToFind);

        }

        return temp;

}

// strCatFiltUrl
function CatFiltBack(url){
//	var url = window.frames['WinSession'].strCatFiltUrl;
	var bEmpty, bStock, bProd;
	var arrProd;
	
	bEmpty 	= 0;
	bStock 	= 0;
	bProd 	= 1;
	
	if(url.length <= 0){
		url = '#' + $('#requestFilter').val() + '&limit=0/0&prod=&pn=&Pg=0'
		bEmpty = 1;	
	}
	var request = '';
	var arrUrl;
	url = url.substring(url.indexOf('#') + 1, url.length);
	request = url.substring(0, url.indexOf('&limit='));
	
	// Ukonceni tlacitka zpet pokud neni stena stranka
//	if(request != $('#requestFilter').val()) return;
	
	url = url.substring(request.length + 1, url.length);

	arrUrl = url.split('&');
	for(var i = 0; i< arrUrl.length ; i++){
		var arrSubUrl = '';
		arrSubUrl = arrUrl[i].split('=');
		
		if(arrSubUrl[0] == 'limit'){
			$('#priceLimit').val(arrSubUrl[1]);
			var arrPrice
			arrPrice = 	arrSubUrl[1].split('/');
			if(arrPrice.length > 1){
				nPriceMinResult = arrPrice[0];
				nPriceMaxResult = arrPrice[1];
			}
		}else if(arrSubUrl[0] == 'Pg'){
			$('#PageID').val(arrSubUrl[1]);
		}else if(arrSubUrl[0] == 'stock'){
			$('#CheckStor').attr('checked', 'checked');
			bStock = 1;			
		}else if(arrSubUrl[0] == 'prod'){			
			var prodList = $("#AdvanceSearchForm input[name='prod']:checked");
			for(var j = 0; j< prodList.length; j++){
				prodList[j].checked = false;
			}
			var prodAll = objGet('prodAll').checked;
			
			if(arrSubUrl[1].substring(arrSubUrl[1].length - 1, arrSubUrl[1].length) == ','){
				arrSubUrl[1] = arrSubUrl[1].substring(0, arrSubUrl[1].length - 1);
			}
			arrProd = arrSubUrl[1].split(',');
			for(var k= 0; k< arrProd.length && bProd == 1; k++){
				if(arrProd[k] == '0' || arrProd[k].length <= 0){
					bProd = 0;
				}
				else{
					bProd = 1;
				}
			}
		}else if(arrSubUrl[0] == 'pn'){
			$('#categorySorter option').attr('selected',false);
			if(arrSubUrl[1].length > 0){
				$('#categorySorter option[value=\'' + arrSubUrl[1] + '\']').attr('selected',true);
			}
		}
	}
	
	if(bStock == 0){
		$('#CheckStor').removeAttr('checked');
	}
	if(bProd == 1){
		$('#prodAll').removeAttr('checked');
		prodListOpen();
		for(var i= 0; i< arrProd.length && bProd == 1; i++){
			$('#prod' + arrProd[i]).attr('checked', 'checked');
		}		
			
	}else{
		prodListClose();
	}
	
	
	InitPrice();
	categoryAjax(request, bEmpty);

}

function bottomCubeEfect(){
	$('#subCat_1 .cube .next').mouseout(function(){
		$('#subCat_1 .cube .next').css('border-style','outset');
		}
	);

	$('#subCat_1 .cube .next').mouseup(function(){
		$('#subCat_1 .cube .next').css('border-style','outset');
		}
	);
	$('#subCat_1 .cube .next').mousedown(function(){
		$('#subCat_1 .cube .next').css('border-style','inset');
		}
	);

	$('#subCat_1 .cube .prev').mouseout(function(){
		$('#subCat_1 .cube .prev').css('border-style','outset');
		}
	);
	$('#subCat_1 .cube .prev').mouseup(function(){
		$('#subCat_1 .cube .prev').css('border-style','outset');
		}
	);
	$('#subCat_1 .cube .prev').mousedown(function(){
		$('#subCat_1 .cube .prev').css('border-style','inset');
		}
	);	


}

function removeAfterPaging(){
	$('#bannerFirstPage').fadeOut('slow', function(){
		$('#bannerFirstPage').remove();
		positionH1New();
		}
	);
	$('#ContentPage #ArticlesText').fadeOut('slow', function(){
		$('#ContentPage #ArticlesText').remove();
		positionH1New();
		}
	);	
	$('#topSale').fadeOut('slow', function(){
		$('#topSale').remove();
	}
	);

}

function categoryNoResultPosition(){
			var categoryFilter = $("#categoryFilter");
			var prodFormList = $('#prodFormList');
			
			// Pocitani top, sirky a vysky
			var top,width,paddingBottom;
			top = categoryFilter.offset().top + categoryFilter.height() + 14;
			if(prodFormList.height() > 0){
				top += prodFormList.height();
			}			
			width = categoryFilter.width() + 10; //categoryFilter.css('padding-left') + categoryFilter.css('padding-right') -  $('#categoryList #noResult').css('padding-left');
			paddingBottom = $('#categoryList').offset().top - top;
			
			$('#categoryList #noResult').css({
				'position':'absolute',
				'top':top,
				'width':width,
				'padding-bottom':paddingBottom
				})
}

function prodAllSet(setVal){
	if(objGet('prodAll') != null) {
		objGet('prodAll').checked = (setVal == 1?true:false);
	}
}

function prodListCheck(bClear){
	if(bClear == 1){
		var prodList = $("#prodFormList input[name='prod']:checked");
		for(var i = 0; i< prodList.length; i++){
			prodList[i].checked = false;
		}
		objGet('prodAll').checked = true;
	}else{
		var prodList = $("#prodFormList input[name='prod']:checked");
		if(prodList.length <= 0){
			if(objGet('prodAll') != null) {
				objGet('prodAll').checked = true;
			}
		}
		else{
			if(objGet('prodAll') != null) {
				objGet('prodAll').checked = false;
			}
		}
	}
	objGet('formSearch').onsubmit();	
}

function prodListChange(){
		var tmpHtml = $('#prodFormListHide').html();
		// Pokud oteviram nebo zaviram tak menim class u odkazu znacek <span class="znacky">
		var znacka = $('.znacka')
		var znackaClassName = znacka.attr('class');
		if(znackaClassName.indexOf('open') > 0){
			$(znacka).removeClass('open');
		}else{
			$(znacka).addClass('open');		
		}
		if(tmpHtml.replace(' ','').replace('\n', '').length > 0){
			$('#prodFormList').css('display','none');
			$('#prodFormListHide').html($('#prodFormList').html());
			$('#prodFormList').html(tmpHtml);
			
			$('#prodFormList').fadeIn('slow');
			
			if($('#categoryList #noResult').length > 0){
				categoryNoResultPosition();
			}
			
		}else{
			var prodAll = objGet('prodAll').checked;
			var prodList = $("#prodFormList input[name='prod']:checked");
			for(var i = 0; i< prodList.length; i++){
				prodList[i].checked = false;
			}
			objGet('prodAll').checked = true;		
			$('#prodFormList').fadeOut('slow',function(){
				$('#prodFormListHide').html($('#prodFormList').html());
				$('#prodFormList').html(tmpHtml);
			});
			
			if($('#categoryList #noResult').length > 0){
				categoryNoResultPosition();
			}
			if(!prodAll){
				objGet('formSearch').onsubmit();
			}
		}		


}


function prodListClose(){
			
	var tmpHtml = $('#prodFormList').html();
	if(tmpHtml.replace(' ','').replace('\n', '').length > 0){
		var znacka = $('.znacka')
		var znackaClassName = znacka.attr('class');
		if(znackaClassName.indexOf('open') > 0){
			$(znacka).removeClass('open');
		}else{
			$(znacka).addClass('open');		
		}

		$('#prodFormList').fadeOut('slow',function(){
			$('#prodFormListHide').html(tmpHtml);
			$('#prodFormList').html("");
		});
	}	
}

function prodListOpen(){
	var tmpHtml = $('#prodFormListHide').html();
	if(tmpHtml.replace(' ','').replace('\n', '').length > 0){
		var znacka = $('.znacka')
		var znackaClassName = znacka.attr('class');
		if(znackaClassName.indexOf('open') <= 0){
			$(znacka).addClass('open');		
		}

		$('#prodFormList').css('display','none');
		$('#prodFormListHide').html($('#prodFormList').html());
		$('#prodFormList').html(tmpHtml);
			
		$('#prodFormList').fadeIn('slow');;
	}	
}


function prodAllSet(setVal){
	if(objGet('prodAll') != null) {
		objGet('prodAll').checked = (setVal == 1?true:false);
	}
}

function ProdListSet(strProd){
	if(strProd == null){strProd = '';}
	var arrProdList = strProd.split('|');
	for(var i = 0; i < arrProdList.length; i++){
		var arrProd = arrProdList[i].split(';');
		$('#prod' + arrProd[0]).attr('disabled', (arrProd[1] == '0'?true:false));
		if(arrProd[1] == '0'){
					$('#prodLbl' + arrProd[0]).removeClass('disabled').addClass('disabled');
		}
		else
		{
			$('#prodLbl' + arrProd[0]).removeClass('disabled');
		}
	}
}

$(document).ready(function(){

	bottomCubeEfect();

	if(!bSearchBot){
		setInterval(function(){
				if(categoryFilterLocationHash != window.location.hash){
					categoryFilterLocationHash = window.location.hash;
					CatFiltBack(categoryFilterLocationHash);
				}
			}
			,250
		);
		
		}
	}
);

