$(document).ready(function() {
    $("a[@href=#]").addClass( 'active-link');
});

// add product to cart
addtocart = function(idProduct, el, attributes, redirectlink) {
    
	// to json not allowed
	// try hack
	var a = {};
	for (var i = 0, len = attributes.length; i < len; i++) {
		a['attributes[' + i + ']'] = attributes[i];
	}
	
    $(el).effect("transfer", {
        className: 'ui-effects-transfer',
        to: "div#cart-storage"
    }, 1500);
    
	a.idProduct = idProduct;
    jQuery.post(
        Core.basepath + '/json/default/cart/addToCart/',
		a, 
        function(response) {
            if (response.success == true) {
				if (redirectlink) {
					window.location.href = redirectlink;
				}
				
                $("div#cart-storage > a > span.num").html(response.total);
            }
        }, 
    'json');
};

price_recalculate = function() {
    var a = $("select[name^=attribute]");
    var price = 0;
    a.each(function(i, cmp) {
            var option = $(cmp.options[cmp.selectedIndex]);
            var value = parseInt(option.attr('price'), 10);
            if (!isNaN(value)) {
                price += value;
            }   
    });
    var value = parseInt($('input#start_product_price').val(), 10);
    if (!isNaN(value)) {
        $('span#product_price').html(value + price);
    }
};

collect_attribute_values = function() {
    var a = $("select[name^=attribute]");
    var values = [];
    a.each(function(i, cmp) {
            values.push($(cmp).val());
    });
    return values;
};

Product = function() {
	return {
		addToCompare: function(id, totalId, groupCls) {
			jQuery.post(Core.basepath + '/json/default/compare/add/', {
				idProduct: id
			}, 
            function(response) {
                $('#' + totalId).html(String(response.total));
				$('.' + groupCls).toggle();
            }, 
            'json');
		},
		
		removeFromCompare: function(id, totalId, groupCls) {
            jQuery.post(Core.basepath + '/json/default/compare/deleteAjax/', {
				idProduct: id
			}, 
            function(response) {
                $('#' + totalId).html(String(response.total));
                $('.' + groupCls).toggle();
            }, 
            'json');
		},
		
		fancybox: function(){
			// change product photo
			var list = $('ul#product-image-gallery');
			var active = $($('ul#product-image-gallery > li').get(0));
			active.addClass('current');
			var image = $('img#product-full-image');
			var a = $('ul#product-image-gallery > li > a');
			a.click(function(){
				image.attr('src', this.href);
				active.removeClass('current');
				var parent = $(this).parent();
				parent.addClass('current');
				active = parent;
				return false;
			});
			image.attr('src', active.find('a').attr('href'));
			image.fancybox({
				'itemLoadCallback': function(opts){
					var imgUrl = active.find('span').html();
					opts.itemArray.push({
						url: imgUrl,
						title: active.find('img').attr('alt') || undefined
					});
					
					a.each(function(i){
						var url = $(this).parent().find('span').html();
						if (imgUrl == url) 
							return true;
						opts.itemArray.push({
							url: url,
							title: $(this).parent().find('img').attr('alt') || undefined
						});
					});
				}
			});
		},
		
		rate: function(rate, idProduct) {
			jQuery.post(Core.basepath + '/json/default/rating/rate/', {
				rate: rate,
                idProduct: idProduct
            }, 
            function(response) {
				var ul = $('#ratig-layer-' + idProduct + ' > div > ul');
				$(ul).find('li').each(function(i, li) {
	                if (!$(li).hasClass('current-rating')) {
						$(li).remove();
					} else if (true == response.success) {
						var rating = response.rating;
						$(li).width(17 * rating);
						$(li).html(rating);
					}
				});
            }, 
            'json');
		}
	};
}();

Location = {};
Location.combo = function(cfg) {
	
	this.otherCaption = null;
	this.otherId = null;
	
	this.countryOriginal = null;
	this.regionOriginal = null;
	this.cityOriginal = null;
	this.autoLoad = false;
	
	cfg = cfg || {};
	// something like Ext.applyIf
	for(var i in cfg) {
		if (!this[i]) {
			this[i] = cfg[i];
		}
	}
	
	this.country = $('#combocountry');
	this.region = $('#comboregion');
	this.city = $('#combocity');
	
	this.altcountry = $('#alternatecountry');
	this.altregion = $('#alternateregion');
	this.altcity = $('#alternatecity');
	
	var self = this;
	
	this.country.change(function(e) {
		if (self.otherId == self.country.val()) {
		    self.disableRegion();
			self.showAltCountry();
//			Shipping.clear();
		} else {
			self.enableRegion();
			self.hideAltCountry();
			self.loadRegions(self.country.val());
		}
	});

    this.region.change(function(e) {
		if (self.otherId == self.region.val()) {
			self.showAltRegion();
			self.disableCity();
		} else {
			self.enableCity();
			self.hideAltRegion();
			self.loadCities(self.country.val(), self.region.val());
		}
//		Shipping.clear();
	});	
	
	this.city.change(function() {
		if (self.otherId == self.city.val()) {
			self.showAltCity();
		} else {
			self.hideAltCity();
		}
//		Shipping.clear();
	});
        
    if (this.autoLoad) {
		this.country.one('load', function() {
			self.loadCountries();
		});
	}    
    Location.combo.constructor.call(this);
};


Location.combo.prototype = {
	
	disableRegion: function() {
		this.region.attr('disabled', true);
        this.showAltRegion();
		this.region.empty();
		this.region.get(0).options.add(new Option(this.otherCaption, this.otherId));
		this.disableCity();
	},
	
	enableRegion: function() {
		this.region.removeAttr('disabled');
		if (this.otherId == this.region.val()) {
			this.showAltRegion();
		} else if (this.region.get(0).options.length > 0) {
			this.hideAltRegion();
		}
	},
        
    disableCity: function() {
        this.city.attr('disabled', true);
        this.city.empty();
        this.city.get(0).options.add(new Option(this.otherCaption, this.otherId));
        this.showAltCity();
    },
    
    enableCity: function() {
        this.city.removeAttr('disabled');
        if (this.otherId == this.city.val()) {
            this.showAltCity();
        } else if (this.city.get(0).options.length > 0) {
            this.hideAltCity();
        }
    },
	
	showAltCountry: function() {
		this.altcountry.show();
        this.altcountry.removeAttr('disabled');
	},
	
	hideAltCountry: function() {
		this.altcountry.hide();
		this.altcountry.val("");
        this.altcountry.attr('disabled', true);
	},
	
	showAltRegion: function() {
		this.altregion.show();
        this.altregion.removeAttr('disabled');
	},
	
	hideAltRegion: function() {
		this.altregion.hide();
		this.altregion.val("");
        this.altregion.attr('disabled', true);
	},
	
	showAltCity: function() {
		this.altcity.show();
		this.altcity.removeAttr('disabled');
	},
	
	hideAltCity: function() {
		this.altcity.hide();
        this.altcity.val("");
        this.altcity.attr('disabled', true);
	},
	
	loadCountries: function() {
		
		var country = this.country;
		var value = this.countryOriginal;
		var self = this;
        
		jQuery.post(Core.basepath + '/json/default/location/getCountries/', {}, 
		function(response) {
            country.empty();
            var dom = country.get(0);
            var selected = false;
			var hasSelected = false;
            jQuery.each(response.rows, function(i, row) {
                if ((value == row.country_id)
				 || (!value && row.selected == true)
				 ) {
				 	hasSelected = true;
                    selected = true;
                } else {
					selected = false;
				}

                var o = new Option(row.name, row.country_id, null, selected);
                dom.options.add(o);
            });
            dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
            country.trigger('change');
        }, 
        'json');
	},
	
	loadRegions: function(idCountry) {
		var region = this.region;
		var value = this.regionOriginal;
		var self = this;

		jQuery.post(Core.basepath + '/json/default/location/getRegions/', {
			countryId: idCountry
		}, function(response) {
			region.empty();
			var dom = region.get(0);
			var selected = false;
			var hasSelected = false;
			jQuery.each(response.rows, function(i, row) {
				if (value == row.region_id || (!value && row.selected == true)) {
					hasSelected = true;
					selected = true;
				} else {
					selected = false;
				}
				var o = new Option(row.name, row.region_id, null, selected);
				dom.options.add(o);
			});
			dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
			region.trigger('change');
		}, 
		'json');
	},

    loadCities: function(idCountry, idRegion) {
	    var city = this.city;
		var self = this;
		var value = this.cityOriginal;
		jQuery.post(Core.basepath + '/json/default/location/getCities/', {
            countryId: idCountry,
			regionId: idRegion
        }, function(response) {
			city.empty();
            var dom = city.get(0);
			var selected = false;
			var hasSelected = false;
            jQuery.each(response.rows, function(i, row) {
				if (value == row.city_id || (!value && row.selected == true)) {
					hasSelected = true;
					selected = true;
				} else {
					selected = false;
				}
                var o = new Option(row.name, row.city_id, null, selected);
                dom.options.add(o);
            });
			dom.options.add(new Option(self.otherCaption, self.otherId, null, !hasSelected));
			city.trigger('change');
        }, 
        'json');
	}
};

Shipping = function() {
	
	return {
		
		fetch: function() {
			return $('#shippingtypes input[name=shippings]');
		},
		
		fetchPriceCaption: function(id) {
			return $('#shipping_price_' + id);
		},
		
		check: function(location) {
//			this.clearAll();
			var self = this;
			var p = {};
			if (location) {
				p = {
					country: location.country.val(),
	                region: location.region.val(),
	                city: location.city.val()
				};
			}
			jQuery.post(Core.basepath + '/json/default/order/shippingtype/', p, 
			function(o, success){
				self.checkCallback(o, success);
			}, 'json');
		},
		
		checkCallback: function(o, success) {
			if (true !== o.success) {
                this.clearAll();
                this.disableAll();
                return;
            }
			
            var types = o.types;
			var self = this;
			
            this.fetch().each(function(i, el) {
                var input = $(el);
				var id = parseInt(input.val(), 10);
				var disabled = true;
				var price = 0;

				for (var i = 0, len = types.length; i < len; i++) {
					
	                if (id == types[i].id) {
						disabled = false;
						price = types[i].price;
					}
	            }
				
				self.fetchPriceCaption(input.val()).html(String(price) + ' ' + o.abbreviation);
				if (disabled) {
					input.removeAttr('checked');
					input.attr('disabled', true);
				} else {
					input.removeAttr('disabled');
				}
		    });
		},
		
		disableAll: function() {
			this.fetch().each(function(i, el) {
                $(el).attr('disabled', true);
            });
		},
		
		clearAll: function() {
			this.fetch().each(function(i, el) {
				$(el).attr('checked', false);
			});
		},
		
		save: function(radio) {
			jQuery.post(Core.basepath + '/json/default/order/shipping/', {
		        shipping: $(radio).val()
		    }, function(o, success) {}, 'json');
		},
		
		saveAddress: function() {
		    var form = $('[name=location]');
		    var params = {};
		    form.find('input,select').each(function(i, el) {
		            var element = $(el);
		            if (element.attr('disabled') || -1 == element.val()) {
		                return;
		            }
		
		            params['address[' + element.attr('name') + ']'] = element.val();
		    });
		
		    jQuery.post(Core.basepath + '/json/default/order/contact/', 
		        params, 
		        function(o, success) {
		        if (o.success == true) {
		            $('#order_address').html(o.completeAddress);
		            $('#order_address_helper > div').toggle();
		        }
		    }, 'json');
		}
	};
}();

Payments = function() {
	
	return {
		savePayments: function(radio){
            
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
				payments: $(radio).val()
			}, function(o, success){
				if (true !== o.success) {
					$(radio).attr('checked', false);
				}
				
				$('input[name=payments]').each(function(i, input) {
                    var c = $(input);
					var checked = $(radio).val() == c.val();
					$('#payment_' + c.val()).find('input[type=radio]').each(function(j, item) {
						if (checked) {
						   $(this).removeAttr('disabled');	
						} else {
							$(this).attr('disabled', true);
							$(this).attr('checked', false);
						}
                    });
                });
			}, 'json');
		},
		
		savePurse: function(radio){
			
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
				purseid: $(radio).val()
			}, function(o, success){
				if (true !== o.success) {
					$(radio).attr('checked', false);
				}
			}, 'json');
		},
		
		saveCashless: function(radio) {
			
			jQuery.post(Core.basepath + '/json/default/order/payments/', {
                cashlesstypeid: $(radio).val()
            }, function(o, success){
                if (true !== o.success) {
                    $(radio).attr('checked', false);
                }
            }, 'json');
		}
	};
}();

Commentary = function() {
	return {
		click: function(element, showEl, hideEl) {
			
			var parent = $(element).parent();
			if (parent.hasClass('current')) {
				return;
			}
			
			$('#' + showEl).hide();
			$('#' + hideEl).show();
			parent.parent().children().each(function(i, el) {
                $(el).removeClass('current');
            });
			parent.addClass('current');
		}
	};
}();

function NewOdnaknopka3() {
this.domain=location.href+'/';
this.domain=this.domain.substr(this.domain.indexOf('://')+3);
this.domain=this.domain.substr(0,this.domain.indexOf('/'));
this.location=false;
this.selection=function() {
var sel;
if (window.getSelection) sel=window.getSelection();
else if (document.selection) sel=document.selection.createRange();
else sel='';
if (sel.text) sel=sel.text;
return encodeURIComponent(sel);
}
this.url=function(system) {
var title=encodeURIComponent(document.title);
var url=encodeURIComponent(location.href);
switch (system) {
case 1: return 'http://memori.ru/link/?sm=1&u_data[url]='+url+'&u_data[name]='+title;
case 2: return 'http://bobrdobr.ru/addext.html?url='+url+'&title='+title;
case 3: return 'http://www.google.com/bookmarks/mark?op=add&bkmk='+url+'&title='+title;
case 4: return 'http://zakladki.yandex.ru/userarea/links/addfromfav.asp?bAddLink_x=1&lurl='+url+'&lname='+title;
case 5: return 'http://twitter.com/home?status='+title+' '+url;
case 6: return 'http://del.icio.us/post?v=4&noui&jump=close&url='+url+'&title='+title;
case 7: return 'http://text20.ru/add/?source='+url+'&title='+title+'&text='+this.selection();
case 8: return 'http://news2.ru/add_story.php?url='+url;
case 9: return 'http://www.mister-wong.ru/index.php?action=addurl&bm_url='+url+'&bm_description='+title;
case 10: return 'http://moemesto.ru/post.php?url='+url+'&title='+title;
case 11: return 'http://smi2.ru/add/?url='+url+'&precaption='+title;
case 12: return 'http://vkontakte.ru/share.php?url='+url;
case 13: return 'http://www.vaau.ru/submit/?action=step2&url='+url;
case 14: return 'http://myscoop.ru/add/?URL='+url+'&title='+title;
case 15: return 'http://www.linkstore.ru/servlet/LinkStore?a=add&url='+url+'&title='+title;
case 16: return 'http://www.ruspace.ru/index.php?link=bookmark&action=bookmarkNew&bm=1&url='+url+'&title='+title;
case 17: return 'http://www.100zakladok.ru/save/?bmurl='+url+'&bmtitle='+title;
}
}
this.redirect=function() {
if (this.location) location.href=this.location;
this.location=false;
}
this.go=function(i) {
this.location=this.url(i);
setTimeout('odnaknopka3.redirect()',2000);
var scr=document.createElement('script'); 
scr.type='text/javascript'; 
scr.src='http://odnaknopka.ru/save2/?domain='+this.domain+'&system='+i; 
document.body.appendChild(scr);
return false;
}
this.init=function() {
var titles=new Array('Memori','&#1041;&#1086;&#1073;&#1088;&#1044;&#1086;&#1073;&#1088;','&#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1082;&#1080; Google','&#1071;&#1085;&#1076;&#1077;&#1082;&#1089;.&#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1082;&#1080;','Twitter','del.icio.us','&#1058;&#1077;&#1082;&#1089;&#1090; 2.0','News2','&#1052;&#1080;&#1089;&#1090;&#1077;&#1088; &#1042;&#1086;&#1085;&#1075;','&#1052;&#1086;&#1105;&#1052;&#1077;&#1089;&#1090;&#1086;','&#1057;&#1052;&#1048; 2','&#1042;&#1072;&#1072;&#1091;!','AddScoop','LinkStore','RuSpace','&#1057;&#1090;&#1086; &#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1086;&#1082;');
var html='';
html+='<a href="#"><img src="http://ereaders.com.ua/html/images/blank.gif" width="16" height="16" alt=" #" title="&#1054;&#1076;&#1085;&#1072;&#1050;&#1085;&#1086;&#1087;&#1082;&#1072;" style="border:0;padding:0;margin:0 4px 0 0;background:url(http://ereaders.com.ua/html/images/panel.png) no-repeat -270px -256px"/></a>';
for (i=0;i<10;i++) {
html+='<a href="'+this.url(i+1)+'" onclick="return odnaknopka3.go('+(i+1)+');"><img src="http://ereaders.com.ua/html/images/blank.gif" width="16" height="16" alt=" #" title="'+titles[i]+'" style="border:0;padding:0;margin:0 4px 0 0;background:url(http://ereaders.com.ua/html/images/panel.png) no-repeat -270px -'+(i*16)+'px"/></a>';
}
document.write(html);
}
}


var
  vk_members_data = {},
  lastCommentsResponse,
  lastCommentsPage = null,
  baseURL = window.location.protocol + '//' + window.location.hostname + '/';

function array_unique(ar){
  if (ar.length && typeof ar !== 'string') {
    var sorter = {};
    var out = [];
    for (var i=0, j=ar.length; i<j; i++) {
      if(!sorter[ar[i]+typeof ar[i]]){
        out.push(ar[i]);
        sorter[ar[i]+typeof ar[i]]=true;
      }
    }
  }
  return out || ar;
}

if (!window.VK) window.VK = {};
if (!VK.Share) {
  VK.Share = {
    _popups: [],
    _gens: [],
    _base_domain: '',
    _ge: function(id) {
      return document.getElementById(id);
    },
    button: function(gen, but, index) {
      if (!gen) gen = {};
      if (gen === gen.toString()) gen = {url: gen.toString()};
      if (!gen.url) gen.url = location.toString();

      if (!but) but = {type: 'round'};
      if (but === but.toString()) but = {type: 'round', text: but};
      if (!but.text) but.text = 'Сохранить';

      var old = true, count_style = 'display: none', count_width = 22;
      if (index === undefined) {
        gen.count = 0;
        gen.shared = (but.type == 'button' || but.type == 'round') ? false : true;
        this._gens.push(gen);
        this._popups.push(false);
        index = this._popups.length - 1;
        old = false;
      } else {
        if ((gen.count = this._gens[index].count) && (but.type == 'button' || but.type == 'round')) {
          count_style = '';
          count_width = 29;
        }
        gen.shared = this._gens[index].shared;
        this._gens[index] = gen;
      }

      var head = document.getElementsByTagName('head')[0];
      if (!this._base_domain) {
        for (var elem = head.firstChild; elem; elem = elem.nextSibling) {
          var m;
          if (elem.tagName && elem.tagName.toLowerCase() == 'script' && (m = elem.src.match(/(http:\/\/(?:[a-z0-9_\-]*\.)?(?:vk\.com|vkontakte\.ru)\/)js\/api\/share\.js(?:\?|$)/))) {
            this._base_domain = m[1];
          }
        }
      }
      if (!this._base_domain) {
        this._base_domain = 'http://vkontakte.ru/';
      }
      if (!old && (but.type == 'button' || but.type == 'round')) {
        var elem = document.createElement('script');
        elem.src = this._base_domain + 'share.php?act=count&index=' + index + '&url=' + encodeURIComponent(gen.url);
        head.appendChild(elem);
      }
      if (but.type == 'button' || but.type == 'button_nocount') {
        return '<table cellspacing="0" cellpadding="0" id="vkshare' + index + '" onmouseover="VK.Share.change(1, ' + index + ');" onmouseout="VK.Share.change(0, ' + index + ');" onmousedown="VK.Share.change(2, ' + index + ');" onmouseup="VK.Share.change(1, ' + index + ');" onclick="VK.Share.click(' + index + ');" style="width: auto; cursor: pointer; border: 0px;"><tr style="line-height: normal;"><td></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798;"><div style="border: 1px solid #5c82ab; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px; font-size: 10px; font-family: tahoma;">' + but.text + '</div></div></td>' +
               '<td style="vertical-align: middle;"><div style="background: url(http://vk.com/images/btns.png) 0px 0px no-repeat; width:' + count_width + 'px; height: 21px"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #a2b9d3; border-left: 0px; background-color: #dee6f1; height: 15px; padding: 2px 4px 0px 2px; font-size: 10px; font-family: tahoma;' + count_style + '">' + gen.count + '</div></td>' +
               '</tr></table>';
      } else if (but.type == 'round' || but.type == 'round_nocount') {
        return '<table cellspacing="0" cellpadding="0" id="vkshare' + index + '" onmouseover="VK.Share.change(1, ' + index + ');" onmouseout="VK.Share.change(0, ' + index + ');" onmousedown="VK.Share.change(2, ' + index + ');" onmouseup="VK.Share.change(1, ' + index + ');" onclick="VK.Share.click(' + index + ');" style="width: auto; cursor: pointer; border: 0px;"><tr style="line-height: normal;">' +
               '<td style="vertical-align: middle;"><div style="height: 21px; width: 2px; background: url(http://vk.com/images/btns.png) no-repeat -21px -42px;"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #3b6798; border-left: 0px;"><div style="border: 1px solid #5c82ab; border-left: 0px; border-top-color: #7e9cbc; background-color: #6d8fb3; color: #fff; text-shadow: 0px 1px #45688E; height: 15px; padding: 2px 4px 0px 6px; font-family: tahoma; font-size: 10px;">' + but.text + '</div></div></td>' +
               '<td style="vertical-align: middle;"><div style="background: url(http://vk.com/images/btns.png) 0px -21px no-repeat; width:' + count_width + 'px; height: 21px"></div></td>' +
               '<td style="vertical-align: middle;"><div style="border: 1px solid #a2b9d3; border-width: 1px 0px; background-color: #dee6f1; height: 15px; padding: 2px 3px 0px 2px; font-size: 10px; font-family: tahoma;' + count_style + '">' + gen.count + '</div></td>' +
               '<td style="vertical-align: middle;"><div style="background: url(http://vk.com/images/btns.png) -27px -42px; width: 2px; height: 21px;' + count_style + '"></div></td>' +
               '</tr></table>';
      } else if (but.type == 'link') {
        return '<table style="width: auto; cursor: pointer; line-height: normal;" onmouseover="this.rows[0].cells[1].firstChild.style.textDecoration=\'underline\'" onmouseout="this.rows[0].cells[1].firstChild.style.textDecoration=\'none\'" onclick="VK.Share.click(' + index + ')" cellspacing="0" cellpadding="0"><tr style="line-height: normal;">' +
               '<td style="vertical-align: middle;"><img src="http://vk.com/images/vk16.png" style="vertical-align: middle;"/></td>' +
               '<td style="vertical-align: middle;"><span style="padding-left: 5px; color: #2B587A; font-family: tahoma; font-size: 11px;">' + but.text + '</span></td>' +
               '</tr></table>';
      } else if (but.type == 'link_noicon') {
        return '<span style="cursor: pointer; font-family: tahoma; font-size: 11px; color: #2B587A; line-height: normal;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'" onclick="VK.Share.click(' + index + ');">' + but.text + '</span>';
      } else {
        return '<span style="cursor: pointer" onclick="VK.Share.click(' + index + ');">' + but.text + '</span>';
      } 
    },
    change: function(state, index) {
      var row = this._ge('vkshare' + index).rows[0];
      var elem = row.cells[1].firstChild.firstChild;
      if (state == 0) {
        elem.style.backgroundColor = '#6d8fb3';
        elem.style.borderTopColor = '#7e9cbc';
        elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#5c82ab';
      } else if (state == 1) {
        elem.style.backgroundColor = '#84a1bf';
        elem.style.borderTopColor = '#92acc7';
        elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderBottomColor = '#7293b7';
      } else if (state == 2) {
        elem.style.backgroundColor = '#6688ad';
        elem.style.borderBottomColor = '#7495b8';
        elem.style.borderLeftColor = elem.style.borderRightColor = elem.style.borderTopColor = '#51779f';
      }
      var left = row.cells[0].firstChild;
      if (left) {
        if (state == 0) {
          left.style.backgroundPosition = '-21px -42px';
        } else if (state == 1) {
          left.style.backgroundPosition = '-23px -42px';
        } else if (state == 2) {
          left.style.backgroundPosition = '-25px -42px';
        }
      }
    },
    click: function(index) {
      var details = this._gens[index];
      if (!details.shared) {
        VK.Share.count(index, details.count + 1);
        details.shared = true;
      }
      var undefined;
      if (details.noparse === undefined) {
        details.noparse = details.title && details.description && details.image;
      }
      details.noparse = details.noparse ? 1 : 0;

      var params = {url: details.url};
      var fields = ['title', 'description', 'image', 'noparse'];
      for (var i = 0; i < fields.length; ++i) {
        if (details[fields[i]]) {
          params[fields[i]] = details[fields[i]];
        }
      }
      params['title'] = document.title;
      params['image'] = document.getElementById('image1').src;
      params['noparse'] = 1;
      var popupName = '_blank';
      var width = 554;
      var height = 349;
      var left = (screen.width - width) / 2;
      var top = (screen.height - height) / 2;
      var popupParams = 'scrollbars=0, resizable=1, menubar=0, left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', toolbar=0, status=0';
      var popup = this._popups[index] = window.open('', popupName, popupParams);
      try {
        var text = '<form accept-charset="UTF-8" action="' + this._base_domain + 'share.php" method="POST" id="share_form">';
        for (var i in params) {
          text += '<input type="hidden" name="' + i + '" value="' + params[i].toString().replace(/"/g, '&quot;') + '" />';
        }
        text += '</form>';
        text += '<script type="text/javascript">document.getElementById("share_form").submit()</script>';

        text = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' +
               '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' +
               '<head><meta http-equiv="content-type" content="text/html; charset=windows-1251" /></head>' +
               '<body>' + text + '</body></html>';
        popup.document.write(text);
      } catch (e) {
      }
      popup.blur();
      popup.focus();
    },
    count: function(index, count) {
      this._gens[index].count = count;
      var elem = this._ge('vkshare' + index);
      if (elem) {
        var row = elem.rows[0];
        if (count) {
          row.cells[3].firstChild.innerHTML = count;
          row.cells[2].firstChild.style.width = '29px';
          row.cells[3].firstChild.style.display = 'block';
          if (row.cells.length > 4) {
            row.cells[4].firstChild.style.display = 'block';
          }
        } else {
          row.cells[2].firstChild.style.width = '22px';
          row.cells[3].firstChild.style.display = 'none';
          if (row.cells.length > 4) {
            row.cells[4].firstChild.style.display = 'none';
          }
        }
      }
    }
  }
}
