var num = parseFloat('10.1')*5;
point = ',';
if(num>50) {
	point = '.';
}

// if point=='.'
// number(5.3) => 5.3
// number(5,3) => 5.3
function number(num)
{
	var myString = 0;
	if (num) {
		myString = new String(num); //String переменная
		if (point=='.') {
			myString = myString.replace(",",".");
		} else {
			myString = myString.replace(".",",");
		}
	}
	num = parseFloat(myString);
	if(isNaN(num)) {
		num = 0;
	}
	return num;
}

function TabSW( aTab )
{
    var i=1;
    while(document.getElementById("tab"+i)){ 
        if ( aTab == i) {
            document.getElementById("tab"+i).style.display = 'block';
        }else{
            document.getElementById("tab"+i).style.display = 'none';
        }	
        i++;
    }
}
function Cart( sw )
{
    if (sw ==1){
        document.getElementById("incart").style.display = 'block';
        document.getElementById("cart_open").style.display = 'none';
    }	else{
        document.getElementById("incart").style.display = 'none';
        document.getElementById("cart_open").style.display = 'block';
    }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function toggleUlMenu (el) {
    var ul = null;
    var childs = el.childNodes;
    for (var i = 0; i<childs.length; i++) {
        if (childs[i].tagName == 'UL') {
            ul = childs[i];
        }
    }
    if (ul) {
        if (ul.style.display == '')	{
            childs = ul.getElementsByTagName('UL');
            for (var i = 0; i<childs.length; i++) {
                childs[i].style.display = 'none';
            }
            ul.style.display = 'none';
        } else {
            ul.style.display = '';
        }
    }
    if (el.parentNode.id && el.parentNode.parentNode.tagName != 'UL' && el.parentNode.parentNode.tagName != 'LI') {
        childs = el.parentNode.childNodes;
        for (var i = 0; i<childs.length; i++) {
            if (childs[i].tagName == 'LI' && childs[i] != el) {
                var uls = childs[i].getElementsByTagName('UL');
                for (var j=0; j<uls.length; j++) {
                    uls[j].style.display = 'none';
                }
            }
        }
        
    }
}

function rollMenu(except, subcat, suba)
{
	var node = null;
	var i = 1;
	while(node=document.getElementById(subcat+i)) {
		if(except!=i) {
			node.style.display = 'none';
			if(node=document.getElementById(suba+i)) {
				node.className='';
			}
		}
		i++;
	}
}

function toggleMenu (el) 
{
	var ul = null;
	//var id = null;
	//id = document.getElementById(el);
	var childs = document.getElementById(el).childNodes;
	
	for (var i = 0; i<childs.length; i++) {
		if (childs[i].tagName == 'UL') {
			ul = childs[i];
		}
		
		if (childs[i].tagName == 'A') {
			childs[i].className = (childs[i].className=='active' ? '' : 'active');
		}
	}
	
	if (ul) {
		if (ul.style.display == '')	{
			childs = ul.getElementsByTagName('UL');
			for (var i = 0; i<childs.length; i++) {
				childs[i].style.display = 'none';
			}
			ul.style.display = 'none';
		} else {
			ul.style.display = '';
		}
	}
	return false
}


function toggleCart()
{
	if ($("#incart").css("display") == 'none') {
		$("#cart_open").hide();
		$("#cart_close").show();
	}
	
	$("#incart").slideToggle("normal", function() {
	
			if (this.style.display == 'none') {
				$("#cart_open").show();	
			}
			
			createCookie('cart_state', (this.style.display == 'none' ? 'close' : 'open'), 0);
			}
		);
    
}

function toggleFilters()
{
    if ($("#side_filters").css("display") == 'none') {
        $("#side_filters_open").hide();
    }
    $("#side_filters").slideToggle("normal", function() {
                                                if (this.style.display == 'none') {
                                                    $("#side_filters_close").hide();
                                                    $("#side_filters_open").show();
                                                } else {
                                                    $("#side_filters_open").hide();
                                                    $("#side_filters_close").show();
                                                }
                                                createCookie('filters_state', (this.style.display == 'none' ? 'close' : 'open'), 0);
                                             });
}

function move_analogs (dir)
{
    var start_ind = -1;
    var stop_ind = -1;
    var items = $("#analogs > .item");
    var count = items.length;
    if (count>3) {
        var ind = 0;
        var first = -1;
        var last = -1;
        items.each(function() {
            if (first<0 && $(this).css("display") != 'none') {
                first = ind;
            }
            if ($(this).css("display") != 'none') {
                last = ind;
            }
            ind++;
        });
        if (last - first == 2) {
            if (dir == 'left' && first > 0) {
                $(items.get(last)).hide();
                $(items.get(first-1)).show();
            }
            if (dir == 'right' && last < count-1) {
                $(items.get(first)).hide();
                $(items.get(last+1)).show();
            }
        }
    }
}

var analogs_animate = 0;
function move_analogs_anim (dir, item_size, item_count)
{
    if (!analogs_animate) {
        if (dir == 'left') {
            if (parseInt($("#analogs_inner").css("left"))<0) {
                analogs_animate = 1;
                $("#analogs_inner").animate({left: parseInt($("#analogs_inner").css("left")) + item_size + 'px'}, 500, function() {analogs_animate = 0});                
            }
        } else if (dir == 'right') {
            if (parseInt($("#analogs_inner").css("left")) > item_size * item_count - parseInt($("#analogs_inner").css("width"))) {
                analogs_animate = 1;
                $("#analogs_inner").animate({left: parseInt($("#analogs_inner").css("left")) - item_size + 'px'}, 500, function() {analogs_animate = 0});
            }
        }
    }
}


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
function win_popup(url,width,heigh,win)
{
	var win_handle = window.open(url,win,'height='+heigh+',width='+width+',resizable=yes,scrollbars=yes,toolbar=no,status=no,location=no,menubar=no');
	win_handle.window.focus();
}

function win_popup_menu(url,width,heigh,win)
{
	var win_handle = window.open(url,win,'height='+heigh+',width='+width+',resizable=yes,scrollbars=yes,toolbar=no,status=no,location=no,menubar=yes');
	win_handle.window.focus();
}

function open_window(url,width,heigh) 
{
	win_popup(url,width,heigh,'compare');
}

function open_window_order(url,width,heigh) 
{
	win_popup(url,width,heigh,'order');
}

//тСМЙЖХЪ ДКЪ БШАНПЙХ ГЮДЮММНЦН cookie МЮ JavaScript
//var cook_uname = GetCookie('uname');
function GetCookie (name) 
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var endstr = 0;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			endstr = document.cookie.indexOf (";", j);
			if (endstr == -1){
				endstr = document.cookie.length;
			}
			return unescape(document.cookie.substring(j, endstr));
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) { break; }
	}
	return null;
}

function setTitle(my, title)
{
	if(my.value=='') {
		my.value=title;
	}
}

function clearField(my, title)
{
	if(my.value==title) {
		my.value='';
	}
}

function removeFocusOnAllLinks()
{  
	for(var i=0; i<document.links.length; i++) {
		document.links[i].onfocus=blurLink;
	}
}

function blurLink() 
{
	if (this.blur) {
		this.blur();
	}
}

//window.onload=removeFocusOnAllLinks; 

function showLoader()
{
	var txt = '<div id="jquery-overlay" style="background-color:rgb(0, 0, 0); opacity:0.6; width:1263px; height:2049px; left:0pt; line-height:0pt; position:absolute; text-align:center; top:0pt; width:100%; z-index:100;"></div>';
	$("body").append(txt);
	
	txt = "<div id='TB_load'><img src='/img/js/loadingAnimation.gif' onload=''/></div>";
	$("body").append(txt);
	$('#TB_load').show();
}
function removeLoader()
{
	$("#jquery-overlay").remove();
	$("#TB_load").remove();
}




function SW( aTab )
{
	var i=1;
	while(i<10){
		if(document.getElementById("sub"+i)){
			if ( aTab == i) {
				document.getElementById("sub"+i).style.display = 'block';
			}else{
				document.getElementById("sub"+i).style.display = 'none';
			}	
		}
		i++;
	}
}

function Hide( )
{
	var i=1;
	while(i<10){
		if(document.getElementById("sub"+i)){
			document.getElementById("sub"+i).style.display = 'none';
		}
		i++;
	}
}
function Cart( sw )
{
	if (sw ==1){
		document.getElementById("incart").style.display = 'block';
		document.getElementById("cart_open").style.display = 'none';
		}	else{
		document.getElementById("incart").style.display = 'none';
		document.getElementById("cart_open").style.display = 'block';
		}
}

function showHint(input, value) 
{
	if (input.value == '') input.value = value;
}

function hideHint(input, value)
{
	if (input.value == value) input.value = '';
}


function center(el)
{
		var y = $(window).attr('scrollY') || 0;
		
		el.css("position","absolute");
		el.css("left", ($(window).width()  - el.width())  / 2 + "px");
	    el.css("top",  ($(window).height() - el.height()) / 2 + y  + "px");
}









/* Быстрая покупка */
var quickOrder = {
		id    : '#quick_order',
		form  : null,

		init : function() {
			var el = $(this.id);
			this.form     = $('form',el);
			this.error.el = $('div.error',el);
			$('.quick_order_status_init',el).show();
			$('.quick_order_status_ok',el).hide();
		},
		setData : function(opt){
			data = opt || {code:0,name:'== unknown =='};
			$('strong.item_name',$(this.id)).html(data.name);
			$('#quick_id',$(this.id)).val(data.code);
		},
		show : function(opt){
			this.init();
			this.setData(opt);
			this.error.hide();
			
			var $self = $(this.id), width=320, height=320,
				left = ($(window).width()-width)/2,
				top  = ($(window).height()-height)/2 + $(document).scrollTop();
			
			if ($.browser.opera) {
				top = (document.documentElement.clientHeight - height)/2 + $(document).scrollTop();
			}
			
			$self.css({left:left, top:top})
				 .fadeIn(function(){$('input:first',$self).focus();});
		},
		hide : function(){
		   $(this.id).fadeOut();
		},
		send : function() {
			var $self = this;
			$self.error.hide();

			var success = $self.validate.isEmail($('#quick_email').val())
					   || $self.validate.isPhone($('#quick_phone').val());
			if (!success) {
				return $self.error.show();
			}

			$.ajax({
				type: 'POST',
				dataType: 'json',
				url:  $self.form.attr('action'),
				data: $self.form.serialize(),						
				success: function(json) {
					var el = $($self.id);
					$('.order_num',el).text(json['id']);
					$('.quick_order_status_init',el).hide();
					$('.quick_order_status_ok',el).show();
					if (pageTracker) {
						pageTracker._trackPageview("/quick_order");
						
						pageTracker._addTrans(
							json['id'], 
							"Protoria",   
							json['operPrice'],
							"0",
							"0",
							"",
							"",
							""
						);

						// add item might be called for every item in the shopping cart
						// where your ecommerce engine loops through each item in the cart and
						// prints out _addItem for each 						
						pageTracker._addItem(
							json['id'],
							json['code'],      
							json['name'],      
							json['operPrice'],
							1
						);						
						pageTracker._trackTrans(); //submits transaction to the Analytics servers
						
					}
				},
				error : function(XMLHttpRequest, textStatus, errorThrown) {
					alert('На стороне сервера возникла ошибка');
				}
			});
		},
		error : {
			el : null,
			show : function() {
				this.el.parent().fadeIn();
			},
			hide : function() {
				this.el.parent().hide();
			}
		},
		validate : {
			isEmail : function(value) {
				var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
				return pattern.test(value);
			},
			isPhone : function(value) {
				var pattern = /^(\([\d]+\))?[\d\-]+$/;
				return pattern.test(value);
			}
		}
	};

$(function() {
	function showForm(el)
	{
		var objPoint1 = $(el).parents('.list_item');//точка зацепа 1 (листалка, Обзоры IT рынка, Новости по товарам)
		var objPoint2 = $(el).parents('.item_2');   //точка зацепа 2 (карточка товара)
		var name = '== error name ==';
		if(objPoint1.get(0)) {
			name = objPoint1.find('>a.item_name:first').html();
		} else if(objPoint2.get(0)) {
			name = objPoint2.parents('.one_block').find('> div.head3 > h1').html();
		}

		var data = {
			code : $(el).next().val(),
			name : name
		}
		
		quickOrder.show(data);
		return true;
	}
	
	$('a.button_quick').click(function(){
		var self = this;
		if (typeof $('#quick_order').get(0) == 'undefined') {
			$.ajax({
			    url: "/ajax/quickorder",
			    type : 'post',
			    success : function(html) {
					if (typeof $('#quick_order').get(0) == 'undefined') {
				        
						$('.main_content').prepend(html);
						showForm(self)

						$.each(['a.closee','a.close_quick'],function(){
							$(quickOrder.id+' '+this).click(function(){
								quickOrder.hide();
								return false;
							});
						});
						
					    $(quickOrder.id+' a.buy_quick').click(function(){
							quickOrder.send();
							return false;
						});
					}
			    }
			});
		} else {
			showForm(self);
		}
		return false;
	});
});

var core = {
	//redirect
	redirect : function(href, options) {
		var o = options;
		if (o && (typeof o.name == 'string')) {
			var expires, value = '';
			if (o.value) {
				value = o.value;
			}
			if (typeof o.days == 'number') {
				var date = new Date();
				date.setTime(date.getTime() + (1000 * 60 * 60 * 24 * o.days));
				expires = "; expires=" + date.toUTCString();
			}
			document.cookie = o.name + '=' + value + expires + '; path=/';
		}

		if (!href || (typeof href == 'undefined')) {
			href = document.location.pathname;
		}
		document.location.href = href;
	},
	
	//show hint in input 
	showHint : function (input, value) {
		if (input.value == '') input.value = value;
	},

	//hide hint in input
	hideHint : function (input, value) {
		if (input.value == value) input.value = '';
	},
		
	randomNumber : function (m, n) {
		m = parseInt(m);
		n = parseInt(n);
		return Math.floor(Math.random() * (n - m + 1)) + m;
	},
	
	//make img grayscale
	grayscaleImage : function (imgObj) {
		var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        
        var imgW = imgObj.width;
        var imgH = imgObj.height;
        canvas.width = imgW;
        canvas.height = imgH;
        
        canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
        
        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }
        
        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
    },
    
    center : function (el) {
		var y = $(window).attr('scrollY') || 0;
		
		el.css("position","absolute");
		el.css("left", ($(window).width()  - el.width())  / 2 + "px");
	    el.css("top",  ($(window).height() - el.height()) / 2 + y  + "px");
	}
}

core.cookie =  {
	create : function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		} else {
			var expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	},

	read : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for ( var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	}
}

$(function() {
	var $el = $('div.content1 div.seoblock');
	
	if ($el.get(0)) {
		$el.parents('div.content1:first').css({'padding-bottom':'210px'});
	}
});
