var loading = new Image;
loading.src = '/images/load.gif';

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;

		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;
		}

		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}
        var ret = new Array(pageWidth,pageHeight) ;
		return ret;
	}

function tolastpage(target) {
	if(parseInt(Global.catID)>0 && Global.catID!='')   { catStr = Global.catID+'/'; } else { catStr=''; }
	if(parseInt(Global.brandID)>0) {
	    if(catStr=='') brandStr = 'brandID='+Global.brandID;
		brandStr = '&brandID='+Global.brandID;
	} else { brandStr=''; }
	if(parseInt(Global.pol)>0)     {
		if(brandStr=='') polStr = 'pol='+Global.pol;
		polStr = '&pol='+Global.pol;
	} else { polStr=''; }
	if(parseInt(Global.year)>0)    { yearStr = '&year='+Global.year; } else { yearStr=''; }
	if(parseInt(Global.costFrom)>0){ costFrom = '&costFrom='+Global.costFrom; } else { costFrom=''; }
	if(parseInt(Global.costTo)>0)  { costTo = '&costTo='+Global.costTo; } else { costTo=''; }
	if(parseInt(Global.nextPage)>0){ nextStr = 'p/'+Global.nextPage+'.html'; } else { nextStr=''; }
	if(parseInt(Global.lastPage)>0){ lastStr = 'p/'+Global.lastPage+'.html'; } else { lastStr=''; }
	switch(target)
	{
		case"left":
		if(lastStr!='')
		{
		link = '/itemlist/'+catStr+lastStr+brandStr+polStr+yearStr+costFrom+costTo;
		document.location.href=link;
		}
		break;
		case"right":
		if(nextStr!='')
		{
		link = '/itemlist/'+catStr+nextStr+brandStr+polStr+yearStr+costFrom+costTo;
		document.location.href=link;
		}
		break;
	}
}
function brandlastpage(target) {
	if(parseInt(Global.nextPage)>0){ nextStr = Global.nextPage+'.html'; } else { nextStr=''; }
	if(parseInt(Global.lastPage)>0){ lastStr = Global.lastPage+'.html'; } else { lastStr=''; }
	switch(target)
	{
		case"left":
		if(lastStr!='')
		{
		link = '/brandlist/'+lastStr;
		document.location.href=link;
		}
		break;
		case"right":
		if(nextStr!='')
		{
		link = '/brandlist/'+nextStr;
		document.location.href=link;
		}
		break;
	}
}

function addtobasket(title, itemID, itemCost)
{
    var itemCount = $('itemcount').value;
    if(!itemCount.match (/^[0-9]*$/)) { alert('Введите количество товара'); return false; }
    if($('razmer')) var razmerID  = $('razmer').value; else var razmerID=0;
    $('holder' + itemID).show();
    new Ajax.Request('/data/ajax.php', {
		parameters:{
		action:  "addtobasket",
		itemID: itemID,
		cost:  itemCost,
		count: itemCount,
		razmer: razmerID,
		},
		method: 'get',
		onSuccess: function(transport) {
		
			// закроем существующий boxB, прежде чем создавать новый!
			if (document.boxB) {
				document.boxB.close();
			}
			
			document.boxB = new Window({
				className: "alphacube",  
				title: "Уведомление",
				width:400, 
				height:140, 
				minimizable: false,
				maximizable: false,
				destroyOnClose: true, 
				recenterAuto:true
			});

			document.boxB.showCenter(true); 
			document.boxB.setHTMLContent('<div class="alphacube_content"><div class="alphacube_message">Товар "<span id="wb_name">Сноуборд Black Fire Kurt (2009-2010)</span>" успешно добавлен в корзину. <br>Вы можете перейти в корзину для оформления заказа или продолжить покупки.</div><div class="alphacube_buttons"><input type="button" class=" ok_button" onclick="javascript:document.location.href = \'/basket.html\'" value="Перейти в корзину"><input type="button" class=" cancel_button" onclick="Dialog.cancelCallback()" value="Продолжить покупки"></div></div>');
			//setTimeout( 'document.boxB.close()', 3000 );

			
			document.getElementById('wb_name').innerHTML = title;
			WindowCloseKey.init();
			
			$('holder' + itemID).hide();
			basket = transport.responseText.evalJSON();
			$('basket').update('<dt>Корзина</dt>' + '<dd>Товаров: ('+ basket.allitems +' шт.)</dd><dd>на сумму '+basket.allsum+' руб.</dd><dd><a href="/basket.html">перейти в корзину</a></dd>');
		}
    });
}

function removefrombasket(itemID)
{
	var dv = $('dv_'+itemID);
	new Ajax.Request('/data/ajax.php', {
    parameters:{
    action:  "removefrombasket",
    itemID: itemID
    },
    method: 'get',
    onSuccess: function(transport) {
	    basket = transport.responseText.evalJSON();
	    $('basket').update('Товаров: ('+ basket.allitems +' шт.) <br>на сумму '+basket.allsum+' руб.<br><a href="/?page=basket&lang=ru">перейти в корзину</a>');
	    $('bstr').update('Товаров в корзине '+basket.allitems+' шт. на сумму '+basket.allsum+' руб.');
	    dv.remove();
	    }
    });
}
function getBodyScrollTop()
{
  return self.pageYOffset ||
    (document.documentElement && document.documentElement.scrollTop) ||
    (document.body && document.body.scrollTop);
}

function show_orderForm()
{
    var pageDim = getPageSize();
	var innerW = pageDim[0];
	var innerH = pageDim[1];
	var innerT = getBodyScrollTop();
	var overlay = Builder.node('div',{id:'ovrl',style:'background:#000;position:absolute;top:0px;left:0px;width:'+innerW+'px; height:'+(innerH)+'px;z-index:1000;'});
	$('body').appendChild(overlay);
	$('ovrl').setOpacity(0.8);
	$('ovrl').onclick = function()
		{
		$('ovrl').remove();
		$('ofzakaz').toggle();
		}
   $('ofzakaz').toggle();
   $('ofzakaz').style.position='absolute';
   $('ofzakaz').style.left=(innerW-383)/2+'px';
   $('ofzakaz').style.top = (innerT+30)+'px';
   $('ovrl').style.zIndex = 2400;

   $('ofzakaz').style.zIndex = 2500;

}
function do_order()
{
   if($('yesitis').checked==true)
   {
   $('orderForm').submit();
   }
}
function do_areyousure()
{
	var e1 = validate($('fname'));
	var e2 = validate($('tel'));
	var e3 = validate($('city'));
	var e4 = validate($('street'));
	var e5 = validate($('dom'));
	var e6 = validate($('rost'));
	var e7 = validate($('ves'));
	var e8 = validate($('razmer'));
	if((e1+e2+e3+e4+e5+e6+e7+e8)>0) { return false; }

	$('doorder').disabled=true;
	$('poles').hide();
	$('sender').show();
	$('yesitis').observe('click',function(){
	if(this.checked==true) $('doorder').disabled=false; else $('doorder').disabled=true;
	});
}
function cloneThisValue(el)
{
	if($('o'+el.name)) var cloneEl = $('o'+el.name);
	cloneEl.update(el.value);
}
function backtoform()
{
	$('poles').show();
	$('sender').hide();
}

function validate(el)
{
  var f = 0; var t = 1;
  if(el.value.length<=0) { el.style.backgroundColor='#ff9999'; return t; } else { el.style.backgroundColor='#99ff99'; return f; }
}

// Раскрытие/скрытие блока поиска
jQuery(document).ready(function() {

	jQuery(".b-search_params-link").click(function(){
		jQuery(".b-search_wrap").toggleClass("b-search_wrap--show");
		return false;
	});

});

// Basket
function refreshCountBasket(itemID, itemCost) {
	
	var itemCount = $('itemcount'+itemID).value;
	if(!itemCount.match (/^[0-9]*$/)) { alert('Введите количество товара'); return false; }

	new Ajax.Request('/data/ajax.php', {
    parameters:{
		action:  "refreshCountBasket",
		itemID: itemID,
		cost: itemCost,
		count: itemCount
    },
    method: 'get',
    onSuccess: function(transport) {
	    basket = transport.responseText.evalJSON();
	    $('basket').update('Товаров: ('+ basket.allitems +' шт.) <br>на сумму '+basket.allsum+' руб.<br><a href="/?page=basket&lang=ru">перейти в корзину</a>');
	    $('bstr').update('Товаров в корзине '+basket.allitems+' шт. на сумму '+basket.allsum+' руб.');
	    }
    });
}

function refreshRazmerBasket(itemID) {
	
    if($('razmerBasket'+itemID)) var razmerid  = $('razmerBasket'+itemID).value; else var razmerid=0;

	if(razmerid) {
		new Ajax.Request('/data/ajax.php', {
		parameters:{
			action:  "refreshRazmerBasket",
			itemID: itemID,
			razmerID: razmerid
		},
		method: 'get',
		onSuccess: function(transport) {
				alert('Размер успешно обновлен!');
			}
		});
	}
}

function catSort() {
	var nameSort = $("catSort").value;
	var href = window.location.href;
	var reg=/sort_type/;

	if (!reg.test(href)) {
		reg = /(\?+)/i;
		if (!reg.test(href)) 
			window.location.href = window.location.href + '?sort_type=' + nameSort;
		else
			window.location.href = window.location.href + '&sort_type=' + nameSort;
	}
	else { 
		reg = /[?&]+sort_type=([^&]*)/i;
		var href=href.replace(reg, "");
		reg = /(\?+)/i;
		if (!reg.test(href)) 
			window.location.href = href + '?sort_type=' + nameSort;
		else
			window.location.href = href + '&sort_type=' + nameSort;
	}
}


