var
	CURR_BEFORE =	'&nbsp;',
	CURR =			'руб.',
	CURR_AFTER =	'';

var SPL =	'}{';

var cart_col_name = 'Наименование';
var cart_col_price = 'Цена';
var cart_col_count = 'Кол-во';
var cart_col_sum = 'Сумма';
var cart_col_type = 'Сумма';

function wshop(url,cart,win)
{
	var self = this;
	var _url = url; // url with hash of prodovator
	var gSellers = []; // global array for this class of sellers
	var _cart = cart;
	var _win = win;
	
	function Seller()
	{
		var id = 0;
		var shopurl = 0;
		var goodsid = []; // creating array
	}
	
	this.findElement = function(arr,id)
	{
		var result = -1;
		jQuery.each(arr, function(i,item)
		{
			if (item.id == id)
			{
				result = i;
				return;
			}
		});
		return result;
	}
	
	this.getSellers = function()
	{
		jQuery.ajaxSetup({"async" : false});
		var Sellers = []; 
		jQuery.getJSON("/wp-content/plugins/wp-shop/goodsuser.php?" + url + "&getuserbygoods&goods=" + getcookie('wpshop_goodsid') + "&nums=" + getcookie('wpshop_num'),
			function(data)
			{
				jQuery.each(data.goods, function(i,item)
				{
					if ((key = self.findElement(Sellers,item.userid)) == -1)
					{
						Sellers.push({'id':item.userid,
								      'shopurl':item.shopurl,
									  'goodsid':[item.id]
									  });
					}
					else
					{
						Sellers[key].goodsid.push(item.id);
					}
					return;
				});
			});
		jQuery.ajaxSetup({"async" : true});
		return Sellers;
	}

	this.getNum = function(gid)
	{
		var g = String(s_goodsid = getcookie('wpshop_goodsid')).split(SPL);
		var n = String(s_goodsid = getcookie('wpshop_num')).split(SPL);
		
		var r = 0;
				
		jQuery.each(g,function(i,item)
		{
			if (item == gid)
			{
				r = i;
				return;
			}
		});			
		return n[r];
	}
	
	this.OpenProdovator = function (id)
	{
		var text_goods = gSellers[id].goodsid.join(SPL);
		var temp = [];
		jQuery.each(gSellers[id].goodsid,function (i,item)
		{		
			temp.push(self.getNum(item));
		});
		jQuery.ajaxSetup({"async" : false});
		
		jQuery.getJSON("/wp-content/plugins/wp-shop/goodsuser.php?" + url + "&createnewgood&goods=" + text_goods + "&nums=" + temp.join(SPL),
			function(data)
			{
				if (_win == "shadow")
				{
					Shadowbox.open({
							content:    '<iframe src="/wp-content/plugins/wp-shop/goodsuser.php?getshop&shopurl=' + gSellers[id].shopurl + '&filename=payments/cpartners_payments.php&partner=' + data.partnerid + '&goodsid=' + data.goodsid + '&userid=' + data.sellerid + '" width="100%" height="100%" style="padding:0px;margin:0px;border:0;"></iframe>',
							player:     "html",
							title:      "Оформление заказа.",
							height:     800,
							width:      1024
							});
				}
				else
				{
					window.open('/wp-content/plugins/wp-shop/goodsuser.php?getshop&shopurl=' + gSellers[id].shopurl + '&filename=payments/cpartners_payments.php&partner=' + data.partnerid + '&goodsid=' + data.goodsid + '&userid=' + data.sellerid,"","menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes,width=1024,height=800,menubar=no,toolbar=no");
				}
			});		
		jQuery.ajaxSetup({"async" : true});
	}
		
	this.Forming = function(_upd)
	{
		_upd = _upd || false;
		var userid = -1;
		var single = false;	
		gSellers = this.getSellers();
		if (gSellers.length == 1)
		{
			single = true;
			jQuery("#different_sellers").html('');		
		}

		if (single)
		{
			if (_upd == true) return;
			
			//single seller
			jQuery.ajaxSetup({"async" : false});
			jQuery.getJSON("/wp-content/plugins/wp-shop/goodsuser.php?" + url + "&createnewgood&goods=" + getcookie('wpshop_goodsid') + "&nums=" + getcookie('wpshop_num'),
				function(data)
				{
					if (_win == "shadow")
					{
						Shadowbox.open({
								content:    '<iframe src="/wp-content/plugins/wp-shop/goodsuser.php?getshop&shopurl=' + gSellers[0].shopurl + '&filename=payments/cpartners_payments.php&partner=' + data.partnerid + '&goodsid=' + data.goodsid + '&userid=' + data.sellerid + '" width="100%" height="100%" style="padding:0px;margin:0px;border:0;"></iframe>',
								player:     "html",
								title:      "Оформление заказа.",
								height:     800,
								width:      1024
								});
					}
					else
					{
						window.open('/wp-content/plugins/wp-shop/goodsuser.php?getshop&shopurl=' + gSellers[0].shopurl + '&filename=payments/cpartners_payments.php&partner=' + data.partnerid + '&goodsid=' + data.goodsid + '&userid=' + data.sellerid,"","menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes,width=1024,height=800,menubar=no,toolbar=no");
					}
				});
			
			jQuery.ajaxSetup({"async" : true});	
			_cart.reset();
		}
		else
		{
			//different sellers
			var i = 0;
			var buttons = '';
			jQuery.each(gSellers,function(i,item)
			{
				buttons += "<button onclick=\"window.__w.OpenProdovator(" + i + ")\">Заказ №" + (i+1) +"</button><br>";							
			});
			
			var text = '<div style="margin:10px 10px;">Для совершения покупок нажмите используйте следующие кнопки:<p>' + buttons + '</p></div>';
			
			
			if (_upd == true && jQuery("#different_sellers").html() == '')
			{
				alert('');
				return;
			}
			jQuery("#different_sellers").html(text);
		
		}	
	}

	_cart.OnUpdate = this.Forming;
	_cart.wps = this;
}

function Cart(eid_mini, eid_cart)
{
	this.mini = document.getElementById(eid_mini);
	this.cart = document.getElementById(eid_cart);
	

	var OnUpdate = undefined;
	var wps = undefined;
	
	this.init = function()
	{
		this.count = 0;
		this.a_id = new Array();
		this.a_key = new Array();
		this.a_name = new Array();
		this.a_href = new Array();
		this.a_num = new Array();
		this.a_cost = new Array();
		this.a_goodsid = new Array();
	}

	this.load = function()
	{
		var count = getcookie('wpshop_count');
		this.count = count ? parseInt(count) : 0;

		if (this.count)
		{
			this.a_id = String(s_id = getcookie('wpshop_id')).split(SPL);
			this.a_key = String(s_id = getcookie('wpshop_key')).split(SPL);
			this.a_name = String(s_name = getcookie('wpshop_name')).split(SPL);
			this.a_href = String(s_href = getcookie('wpshop_href')).split(SPL);
			this.a_num = String(s_num = getcookie('wpshop_num')).split(SPL);
			this.a_cost = String(s_cost = getcookie('wpshop_cost')).split(SPL);
			this.a_goodsid = String(s_goodsid = getcookie('wpshop_goodsid')).split(SPL);
		}
	}

	this.save = function()
	{
		var s_id = this.a_id.join(SPL);
		var s_key = this.a_key.join(SPL);
		var s_name = this.a_name.join(SPL);
		var s_href = this.a_href.join(SPL);
		var s_num = this.a_num.join(SPL);
		var s_cost = this.a_cost.join(SPL);
		var s_goodsid = this.a_goodsid.join(SPL);
		
		setcookie('wpshop_count', this.count, 0, '/');
		setcookie('wpshop_id', s_id, 0, '/');
		setcookie('wpshop_key', s_key, 0, '/');
		setcookie('wpshop_name', s_name, 0, '/');
		setcookie('wpshop_href', s_href, 0, '/');
		setcookie('wpshop_cost', s_cost, 0, '/');
		setcookie('wpshop_num', s_num, 0, '/');
		setcookie('wpshop_goodsid', s_goodsid, 0, '/');	
	}

	this.update = function()
	{
		if (this.count)
		{
			this.content_mini = '<table cellpadding="5" cellspacing="0" border="0" class="wpshop_widget">';
			this.content_cart = 
				'<table class="recycle_bin" cellpadding="5" cellspacing="0" border="0">'+
				'<thead>'+
				'<tr>'+
				'<th class="name">' + window.cart_col_name + '</th>'+
				'<th class="type">' + window.cart_col_type + '</th>'+
				'<th class="cost">' + window.cart_col_price + ' ('+ CURR +')</th>'+
				'<th class="num">'+ window.cart_col_count + '</th>'+
				'<th class="total">' + window.cart_col_sum + ' ('+ CURR +')</th>'+
				'<th class="delete">&nbsp;</th>'+
				'</tr>'+
				'</thead>'+
				'<tbody>';
			
			var i, t, total;
			for (i = 0, total = 0; i < this.count; i++)
			{
				t = parseInt(this.a_cost[i]) * this.a_num[i]
				total += t;
				


				this.content_cart +=
					'<tr class="rb_item" valign="top">' +
					'<td class="rb_name"><a href="'+ this.a_href[i] +'">'+ this.a_name[i] +'</a></td>' +
					'<td class="rb_type">'+ this.a_key[i] +'&nbsp;</td>' +
					'<td class="rb_cost">'+ this.a_cost[i] +'</td>' +
					'<td class="rb_num"><a class="minus" href="#" onmousedown="__cart.minus(\''+this.a_id[i]+'\', \''+this.a_key[i]+'\', 1); return false;">&minus;</a><a class="plus" href="#" onmousedown="__cart.plus(\''+this.a_id[i]+'\', \''+this.a_key[i]+'\', 1); return false;">+</a><input type="text" value="'+ this.a_num[i] +'" size="3" maxlength="6" onchange="__cart.set(\''+this.a_id[i]+'\', \''+this.a_key[i]+'\', this.value); return false;" /></td>' +
					'<td class="rb_total">'+ t +'</td>' +
					'<td class="rb_delete"><a title="Удалить" href="#" onclick="__cart.remove(\''+this.a_id[i]+'\', \''+this.a_key[i]+'\'); return false;" style="text-decoration:none; color:#f00;">&times;</a></td>' +
					'</tr>';
			}
			this.content_cart +=
				'<tfoot>'+
				'<tr>'+
				'<td colspan="4" align="right"><strong>ИТОГО:</strong></td>'+
				'<td class="rb_total cost"><strong>'+total+'</strong></td>'+
				'<td class="rb_delete"><a title="Удалить все" href="#" onclick="if (confirm(\'Очистить корзину?\')) __cart.reset(); return false;" style="text-decoration:none; color:#f00;">&times;</a></td>' +
				'</tr>'+
				'</tfoot>'+
				'</table>';

			this.content_mini +=
				'<tr><td>Позиций:</td><td>'+this.count+'</td></tr>'+
				'<tr><td>На сумму:</td><td>'+total+'&nbsp;'+CURR+'</td></tr>'+
				
				'</table>';	
		}
		else
		{
			this.content_mini = '<div class="minicart">Ваша корзина пуста.</div>';
			this.content_cart = '<div class="minicart">Ваша корзина пуста.</div>';
		}

		if (this.mini)
		{
			this.mini.innerHTML = this.content_mini;
		}
		if (this.cart)
		{
			this.cart.innerHTML = this.content_cart;
			//if (this.mini) this.mini.parentNode.parentNode.style.opacity = 0.33;
		}
		
		if (this.wps !== undefined)
		{
			this.wps.Forming(true);
		}
	}

	this.reset = function()
	{
		this.is_empty = true;
		this.content_mini = '';
		this.content_cart = '';

		setcookie('wpshop_count', null, 0, '/');
		setcookie('wpshop_id', null, 0, '/');
		setcookie('wpshop_key', null, 0, '/');
		setcookie('wpshop_name', null, 0, '/');
		setcookie('wpshop_href', null, 0, '/');
		setcookie('wpshop_cost', null, 0, '/');
		setcookie('wpshop_num', null, 0, '/');
		setcookie('wpshop_goodsid', null, 0, '/');
		
		this.init();
		this.save();
		//location.reload();
		this.update();
	}

	this.add = function(id, key, name, href, cost, num, goodsid)
	{
		var n = this.count;

		for (i = 0; i < this.count; i++)
			if (this.a_id[i] == id && this.a_key[i] == key)
				n = i;
				
		this.a_id[n] = id;
		this.a_key[n] = key;
		this.a_name[n] = name;
		this.a_href[n] = href;
		this.a_cost[n] = cost;
		this.a_goodsid[n] = goodsid;
		this.a_num[n] = this.a_num[n] ? parseInt(this.a_num[n]) + parseInt(num) : parseInt(num);

		if (n == this.count)
			this.count++;

		this.save();
		this.update();
	}
	
	this.remove = function(id, key)
	{
		for (i = 0; i < this.count; i++)
		{
			if (this.a_id[i] == id && this.a_key[i] == key)
			{
				this.a_id.splice(i, 1);
				this.a_key.splice(i, 1);
				this.a_name.splice(i, 1);
				this.a_href.splice(i, 1);
				this.a_cost.splice(i, 1);
				this.a_goodsid.splice(i, 1);
				this.a_num.splice(i, 1);
				this.count--;
				break;
			}
		}
			
		this.save();
		this.update();
	}

	this.set = function(id, key, value)
	{
		for (i = 0; i < this.count; i++)
			if (this.a_id[i] == id && this.a_key[i] == key && (value = parseInt(value)) > 0)
			{
				this.a_num[i] = value;
				break;
			}

		this.save();
		this.update();
	}

	this.plus = function(id, key, value)
	{
		for (i = 0; i < this.count; i++)
			if (this.a_id[i] == id && this.a_key[i] == key)
			{
				this.a_num[i] = parseInt(this.a_num[i]) + parseInt(value);
				break;
			}

		this.save();
		this.update();
	}

	this.minus = function(id, key, value)
	{
		var num;
		for (i = 0; i < this.count; i++)
			if (this.a_id[i] == id && this.a_key[i] == key && (num = parseInt(this.a_num[i])) > 1)
			{
				this.a_num[i] = num - parseInt(value);
				break;
			}

		this.save();
		this.update();
	}

	this.init();
	this.load();
	this.update();
}

function check_user_info()
{
	var
		fio = document.getElementById('fio'),
		company = document.getElementById('company'),
		address = document.getElementById('address'),
		phone = document.getElementById('phone'),
		email = document.getElementById('email'),
		icq = document.getElementById('icq'),
		button = document.getElementById('order_submit');
	
	if (fio.value && company.value && address.value && phone.value && email.value && icq.value)
	{
		button.disabled = false;
		button.style.opacity = 1;
	}
	else
	{
		button.disabled = true;
		button.style.opacity = 0.33;
	}
}

function CheckUrl(url)
{
	var result = false;
	jQuery.ajaxSetup({"async" : false});
	jQuery.getJSON("/wp-content/plugins/wp-shop/goodsuser.php?" + url,
		function(data)
		{
			if (data.error == undefined)
			{
				result = true;
			}
		}
		);
	jQuery.ajaxSetup({"async" : true});
	return result;
}

function CheckInputBox(obj)
{
	if (obj.value == '')
	{
		jQuery(obj).css("border","1px solid blue");		
		jQuery("#wp_status_check_url").html('Локальный режим.');
		jQuery("#wp_status_check_url").css('color','blue');	
	}
	else if (obj.value == 'xml-rpc')
	{
		jQuery(obj).css("border","1px solid blue");		
		jQuery("#wp_status_check_url").html('XML-RPC режим.');
		jQuery("#wp_status_check_url").css('color','blue');	
	}
	else if (CheckUrl(obj.value))
	{
		jQuery(obj).css("border","2px solid green");
		jQuery("#wp_status_check_url").html('Успешная проверка.');
		jQuery("#wp_status_check_url").css('color','green');
		
	}
	else
	{
		jQuery(obj).css("border","2px solid red");
		jQuery("#wp_status_check_url").html('Ошибка URL.');
		jQuery("#wp_status_check_url").css('color','red');		
	}
}

function findPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

var jjj = false;

function showbuybox(id)
{
	var j = jQuery("#wpshop_buy-" + id);
	var a = document.getElementById("wpshop_bag-" + id);
	if (a!=undefined)
	{
		var coord = findPos(a);
		j.appendTo("body");
		j.css("left",coord[0]);
		j.css("top",coord[1] + a.clientHeight);
		j.css("display",'');
	}
}

function hidebuybox(id)
{
	var j = jQuery("#wpshop_buy-" + id);
	setTimeout(function()
	{
		if (jjj == false)
		{
		j.css("display",'none');
		}
	},2000);
}


function addtocart(id, key, name, href, cost, num, goodsid)
{
	window.__cart.add(id, key, name, href, cost, num, goodsid); 
	showbuybox(id);
	alert('Успешно добавлено в корзину!');
}

function uty(id)
{
	jjj = true;
}

