var $j = jQuery.noConflict();

function banner()
{
	var banner = "banner=";
	var bannerStartIndex = document.cookie.indexOf(banner);
	if (bannerStartIndex == -1) return null
	var bannerEndIndex = document.cookie.indexOf(";", bannerStartIndex + banner.length);
	if (bannerEndIndex == -1) bannerEndIndex = document.cookie.length;
	return unescape(document.cookie.substring(bannerStartIndex + banner.length, bannerEndIndex));
}


function bannerS(s,p)
{
	var exp = new Date();
	exp.setDate(exp.getDate()+7)
	exp.toGMTString();
	document.cookie = "banner=" + escape(s) + "; expires="+exp + "; path= "+p+';';
}



$j(document).ready(function(){
	$j('#query').click(function() {
		if(navigator.userAgent.toLowerCase().indexOf('opera') != -1 && window.event.preventDefault) window.event.preventDefault();this.newWindow = window.open('http://lite.webim.ru/come2us/webim/client.php?locale=ru', 'webim_', 'toolbar=0,scrollbars=0,location=0,menubar=0,width=600,height=420,resizable=1');if(this.newWindow!=null){this.newWindow.focus();this.newWindow.opener=window;}return false;
	});
	$j('#sel').submit( function()
	{
		var url = $j('#sel').attr('action');

		var cat = $j('#catID');
		if (cat[0].selectedIndex > 0)
		{
			url = cat[0].value;
		}

		var brand = $j('#brandID');
		if (brand[0].selectedIndex > 0)
		{
			url += 'brand'+brand[0].value+'/';
		}

		var iszakaz = $j('#iszakaz');

		if(iszakaz[0])
		{
			if (iszakaz[0].selectedIndex > 0)
			{
				url += 'iszakaz'+iszakaz[0].value+'/';
			}
		}

		window.location = url;
		return false;
	});
	$j('.counter').keyup(function(e){calculate();});
});

function summ(id,count,price)
{
	var flag = true;
	var summ = 0;
	var c = getCookie();
	var x = new Array();
	if(c)
	{
		for(i=0; i < c.length; i++)
		{
			if(c[i])
			{
				var d = c[i].split(':');
				if( (parseInt(d[0]) >0) && (parseInt(d[1]) > 0) && (parseInt(d[2]) > 0) )
				{
					x.push(d[0]+':'+d[1]+':'+d[2]);
					summ +=d[2]*d[1];
					if(id == d[0])
					{
						flag = false;
					}
				}
			}
		}
	}

	if(flag)
	{
		summ +=price*count;
		x = x ? x.join(',') + ','+id+':'+count+':'+price+',' : id+':'+count+':'+price;
	}

	
	setCookie(x);
	$j('#allSumm').html(triad(summ));
	cartCount();

}

function setCookie(basket)
{
	var exp = new Date();
	exp.setDate(exp.getDate()+7)
	exp.toGMTString();
	document.cookie = "basket=" + escape(basket) + "; expires="+exp + "; path= /;";
}

triad = function (fractNum)
{
	if (typeof(fractNum)=='undefined') fractNum = 0;
	var num = parseInt(fractNum).toString();
	var regEx = /(-?\d+)(\d{3})/;
	while (regEx.test(num)) { num = num.replace(regEx,"$1"+" "+"$2"); }
	return num;
}

function deleteFromCookie(id)
{
	var cn = confirm ('Вы действительно хотите удалить?')
	if (!cn)
	{
		return false;
	}

	var c = getCookie();
	var x = new Array();
	if(c)
	{
		for(i=0; i < c.length; i++)
		{
			if(c[i])
			{
				var d = c[i].split(':');
				if(id != d[0])
				{
					x.push(d[0]+':'+d[1]+':'+d[2]);
				}
			}
		}
	}
	x = x ? x.join(',') : null;
	setCookie(x);
	cartCount();
	$j('#id'+id+'_tr').remove();
	calculate();
}

function calculate()
{

	var cur= ' '+$j('#main_currency').val();
	var ids =$j('.item_ids');
	var price=0;
	for (var i=0; i<ids.length; i++)
	{
		c = parseInt($j('#'+ids[i].id+'_c').val()) > 0 ? parseInt($j('#'+ids[i].id+'_c').val()) : 0;
		s = parseFloat($j('#'+ids[i].id+'_p').text().replace(cur,'').replace(' ',''))*c;
		$j('#'+ids[i].id+'_s').text(triad(s)+cur);
		price +=s;
	}

	$j('#bprice').text(triad(price)+cur);
}

function getCookie()
{
	var prefix = "basket=";
	var cookieStartIndex = document.cookie.indexOf(prefix);
	if (cookieStartIndex == -1)
	return null
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
	if (cookieEndIndex == -1)
	cookieEndIndex = document.cookie.length;
	var arr = unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
	return arr.split(',');

}

function cartCount()
{
	var c = getCookie();
	var count = 0;
	if(c)
	{
		for(i=0; i < c.length; i++)
		{
			if(c[i])
			{
				var d = c[i].split(':');count +=parseInt(d[1]);
			}
		}
	}
	count = count > 0 ? ' ('+count+')' : '';
	$j('#cartCnt').html(count);

}

var voteS = function ()
{
	var voteClick = function(e)
	{
		//alert();
		//var serializedForm = pf.form.serialize($('voteForm'));
		//alert();

		pf.ajax.post({
		'url': '/vote_ajax/',
		'parameters': pf.form.getValues($('voteForm')),
		'onSuccess': function(req)
		{
			$('voteData').innerHTML = req.responseText;
		},
		'onError': function(req)
		{
			debugError('Ошибка запроса!\nСтатус=' + req.statusText);
			serverSetStatus('error');
			if (onerror)
			{
				onerror(req);
			}
		}
		});
		return false;
	}.bind(this);
	if ($('VoteSubmit'))
	$('VoteSubmit').onclick = voteClick;
}

var mainMenu = function (id)
{
    //window.mainMenu = this;

    this.activeSub = $(id);

    this.menuEffectsOff = new pf.Effects({
        'obj': $('mainMenu'),
        'props': 'height',
        'suffixe': 'px',
        'methodName': 'quartOut',
        'path': [0],
        'duration' : 500});

    this.menuEffectsOn = new pf.Effects({
        'obj': $('mainMenu'),
        'props': 'height',
        'suffixe': 'px',
        'methodName': 'quartOut',
        'path': [0],
        'duration' : 500});

    var items = pf.elem.getChildElements($('mainMenu'), 'LI');
    for (var i = items.length-1; i >= 0; i--)
    {
        var a = items[i].getElementsByTagName('A')[0];
        var sub = items[i].getElementsByTagName('UL')[0];

        sub.style.display = 'block';
        sub.setAttribute('_height', sub.offsetHeight);
        sub.style.display = '';

        if (this.activeSub != sub)
        {
            sub.style.height = '0';
        }
        else
        {
            pf.elem.addClass(sub.parentNode, 'sel');
            sub.style.height = sub.offsetHeight + 'px';
        }

        var menuClick = function(e)
        {
            e = pf.evt.e(e);
            var sub = (e.target || e.srcElement).parentNode.getElementsByTagName('UL')[0];
            var active = this.activeSub;

/*
            pf.elem.toggle(window.mainMenu.activeSub);
            pf.elem.toggle(sub);


            this.menuEffectsOff.obj = active.style;
            this.menuEffectsOff.addEvent('onafterplay', function() {pf.elem.delClass(active.parentNode, 'sel')}.bind(this));
            this.menuEffectsOff.continueTo(0);
*/

            if (active)
            {
                pf.elem.delClass(active.parentNode, 'sel');
                active.style.height = '0';
            }

            if (sub == active)
            {
                this.activeSub = null;
                return false;
            }

            this.menuEffectsOn.obj = sub.style;
            this.menuEffectsOn.addEvent('onbeforeplay', function() {pf.elem.addClass(sub.parentNode, 'sel')});
            this.menuEffectsOn.continueTo(sub.getAttribute('_height'));

            this.activeSub = sub;

            return false;
        }.bind(this);

        a.onclick = menuClick;
    }
};

function fWindow(id)
{
	if (!id) return false;

	this.wnd = $(id);
	this.content = $(id+'-content');

	this.openTxt = function(txt)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		this.wnd.style.display = 'block';
		this.wnd.style.top = 0;
	}

	this.openMatherial = function(h, img, txt, event)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		pf.evt.stop(event);
		pf.elem.addClass(this.wnd, 'matherialWnd');
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		this.wnd.style.top = scrollTop + document.body.offsetHeight/2 + 'px';
		this.content.innerHTML = '<h2>'+h+'<\/h2>'+'<img src="'+img+'" alt="'+h+'" />'+txt;

		pf.evt.add(document.body, 'click', wnd.close);
	}

	this.openWarning = function(txt, event)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		pf.evt.stop(event);
		pf.elem.addClass(this.wnd, 'warningWnd');
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		this.wnd.style.top = scrollTop + document.body.offsetHeight/2 + 'px';
		txt += '<button onclick=\'wnd.close(event);$j("#openAddedOk").click();\'>Положить товар в корзину<\/button>';
		this.content.innerHTML = txt;
		this.wnd.style.height = this.wnd.offsetHeight + 'px';

		pf.evt.add(document.body, 'click', wnd.close);
	}

	this.openAdded = function(txt, event)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		pf.evt.stop(event);
		pf.elem.addClass(this.wnd, 'addedWnd');
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		this.wnd.style.top = scrollTop + document.body.offsetHeight/2 + 'px';
		txt += '<button onclick=\'$j("#closeWnd").click();\'>Продолжить покупки<\/button> &nbsp; <button onclick=\'document.location.href="/cart/"\'>Перейти в корзину<\/button>';
		this.content.innerHTML = txt;
		this.wnd.style.height = this.wnd.offsetHeight + 'px';

		pf.evt.add(document.body, 'click', wnd.close);
	}

	this.openPreview = function(ind, event)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		pf.evt.stop(event);
		pf.elem.addClass(this.wnd, 'previewWnd');
		this.content.innerHTML = '';
		this.content.appendChild($('preview').cloneNode(1));

		var images = this.content.getElementsByTagName('IMG');
		images[0].id = 'photo-preview';
		$j('#photo-preview').unbind('click');
		$j('#photo-preview').css({cursor:'default'});
		images[0].src = gal[ind].b.src;
		images[0].height = gal[ind].b.h;
		images[0].width = gal[ind].b.w;

		//this.content.innerHTML +='<div style="clear:both;margin:5px;height:5px;">';
		/*
		for (var i=images.length-1; i > 0; i--)
		{
		images[i].onclick=function()
		{
		$('photo-preview').src = gal[ind].b.src;
		$('photo-preview').height = gal[ind].b.h;
		$('photo-preview').width = gal[ind].b.w;
		}
		}
		*/
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		this.wnd.style.top = scrollTop + document.body.offsetHeight/2 + 'px';
		this.wnd.style.height = this.wnd.offsetHeight + 'px';
		this.wnd.style.width = this.wnd.offsetWidth + 'px';
		this.wnd.style.margin = '-' + this.wnd.offsetHeight/2 + 'px 0 0 -' + this.wnd.offsetWidth/2 + 'px';

		pf.evt.add(document.body, 'click', wnd.close);
	}

	this.openAddress = function(num, link, event)
	{
		this.wnd.style.height = '';
		this.wnd.style.width = '';
		num = num - 1;
		if (!$('addresses')) {alert('нет блока "addresses"'); return false}

		var li = $('addresses').getElementsByTagName('LI');
		pf.evt.stop(event);

		var txt = '<p>Адрес магазина: '+li[num].getElementsByTagName('SPAN')[0].innerHTML+'<br\/>';
		txt += li[num].getElementsByTagName('P')[0].innerHTML+'</p>';
		txt += '<p><a href="'+link+'">Страничка магазина</a></p>';
		this.content.innerHTML = txt;
		
		pf.elem.addClass(this.wnd, 'addressWnd');
		var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
		this.wnd.style.top = scrollTop + document.body.offsetHeight/2 + 'px';
		this.wnd.style.height = this.wnd.offsetHeight + 'px';

		pf.evt.add(document.body, 'click', wnd.close);
	}

	this.close = function(e)
	{
		if (!pf.elem.findAncestor((e.target || e.srcElement), {'hasClass' : 'window'}) || pf.elem.findAncestor((e.target || e.srcElement), {'hasClass' : 'close'}))
		{
			pf.evt.remove(document.body, 'click', wnd.close);
			this.wnd.className = 'window';
		}
	}.bind(this);
}

function setFooter()
{
	var windowHeight = pf.window.getClientHeight();
	if (windowHeight > 0)
	{
		var contentHeight = $('content').offsetHeight;
		var mainMenuHeight = $('mainMenu').offsetHeight;

		var r = (mainMenuHeight+126) > contentHeight+40 ? (mainMenuHeight+126) : contentHeight+40;
		var footerElement = $('foot');
		var footerHeight  = footerElement.offsetHeight;

		//footerElement.style.position = 'absolute';
		//footerElement.style.top = (r) + 'px';
	}
}

function setLayout()
{
    if ($('index-splash')) $('index-splash').style.width = '';
    var width = 1200;
    var windowWidth = pf.window.getClientWidth();
    var layout = $('layout');
    layout.style.width = 'auto';
    if (windowWidth > width)
    {
        pf.elem.addClass(layout, 'border');
        layout.style.width = width + 'px';
        layout.style.marginLeft = (windowWidth - width)/2 + 'px';
    }
    else
    {
        pf.elem.delClass(layout, 'border');
        layout.style.width = '';
        layout.style.marginLeft = '';
    }
    
    if ($('index-splash')) $('index-splash').style.width = $('content').offsetWidth - 310 + 'px'
}

function selector(form, selected)
{
	var p=pf.form.getValues($(form));
	p['change']=selected;
	pf.ajax.get({
	'url': '/selector/',
	'parameters': p,
	'onSuccess': function(req)
	{
		eval(req.responseText);
	},
	'onError': function(req)
	{
		debugError('Ошибка запроса!\nСтатус=' + req.statusText);
		serverSetStatus('error');
		if (onerror)
		{
			onerror(req);
		}
	}
	});
	//p.push({name: 'change', value: selected});
}

function isValidFormOrder(name, phone,email)
{
	if(!name)
	{
		alert('Введите своё имя');
		return false;
	}

	if(!phone)
	{
		alert('Введите свой телефон');
		return false;
	}

	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	if(!pattern.test(email))
	{
		alert('Введите корректный Email');
		return false;
	}

	return true;

}
