/* горизонтальная прокрутка акции*/
$(function(){
  //Get our elements for faster access and set overlay width
  var div = $('div.sc_menu'),
               ul = $('ul.sc_menu'),
               // unordered list's left margin
               ulPadding = 15;

  //Get menu width
  var divWidth = div.width();

  //Remove scrollbars
  div.css({overflow: 'hidden'});

  //Find last image container
  var lastLi = ul.find('li:last-child');

  //When user move mouse over menu
  div.mousemove(function(e){

    //As images are loaded ul width increases,
    //so we recalculate it each time
    var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;

    var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
    div.scrollLeft(left);
  });
});
/* горизонтальная прокрутка акции*/

function makeWnd(wname,w,h,strong) {
if(strong==''||strong==null||typeof(strong)=='undefined') {
	strong = false;
}
posStr='';
sw=screen.width;
sh=screen.height;
ww=sw-400;
wh=sh-275;

if(w>0) ww = w;
if(h>0) wh = h;

posx=(sw-ww)-150;
posy=0;
if(document.all) posStr=',left='+posx+',top='+posy;
else if(document.layers) posStr=',screenX='+posx+',screenY='+posy;

var parm = strong ? 'directories=0,location=0,menubar=0,toolbar=0,titlebar=0,status=0,scrollbars=0,resizable=0' : 'location=0,menubar=1,toolbar=1,status=1,scrollbars=1,resizable=1'

w = open("",wname,parm+",height="+wh+",width="+ww+posStr,true);
w.focus();
return (w);
}

massive_length=6;
colors_= new Array(massive_length); 
colors_[0] = "#FF9966";
colors_[1] = "#FF6633"; 
colors_[2] = "#CC0000"; 
colors_[3] = "#CC6633"; 
colors_[4] = "#993300";
colors_[5] = "#660000"; 
var next_ = 0; 

function Changehead() { 
	headcolor= colors_[next_];/*headcolor - переменной устанавливаешь новый цвет*/ 

	document.getElementById("lastProducts").style.color=headcolor;

	next_++; 
	if(next_>massive_length-1) next_=0; 
		window.setTimeout("Changehead()",350); 
 
}


massive_lengthz=6;
colorsz_= new Array(massive_lengthz); 
colorsz_[0] = "#FFF";
colorsz_[1] = "#f3f8e4"; 
colorsz_[2] = "#c4ff10"; 
colorsz_[3] = "#b9f010"; 
colorsz_[4] = "#a8da0e";
colorsz_[5] = "#96c40c"; 
var nextz_ = 0; 

function Changeopt() { 
	headcolorz= colorsz_[nextz_];/*headcolor - переменной устанавливаешь новый цвет*/ 

	document.getElementById("opts").style.color=headcolorz;

	nextz_++; 
	if(nextz_>massive_lengthz-1) nextz_=0; 
		window.setTimeout("Changeopt()",600); 
 }


function insertIntoFormSmile(textAreaName,smile){


if (document.all[textAreaName]){



	document.all[textAreaName].value+=smile;
}


}
function makeAjaxRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
			}
		}
if (!http_request) {
		alert('В Вашем браузере, вероятно, отключен JavaScript. Если Вы видите это сообщение, пожалуйста, напишите нам в службу поддержки(ссылка КОНТАКТЫ в главном меню, сверху), это очень важно для нас. Спасибо');
		return false;
	}
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}

function alertContents(http_request) {

if (http_request.readyState == 4) {
	if (http_request.status == 200) {
//		alert(http_request.responseText);
		showCart(http_request.responseText);
	} else {
//	alert('С запросом возникла проблема.');
	}
	}
}
function makeAjaxRequestS(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
		} else if (window.ActiveXObject) { // IE
			try {
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
			}
		}
if (!http_request) {
//		alert('Не вышло  Невозможно создать экземпляр класса XMLHTTP ');
		alert('В Вашем браузере, вероятно, отключен JavaScript. Если Вы видите это сообщение, пожалуйста, напишите нам в службу поддержки(ссылка КОНТАКТЫ в главном меню, сверху), это очень важно для нас. Спасибо');
		return false;
	}
http_request.onreadystatechange = function() { alertContentsS(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}

function alertContentsS(http_request) {

if (http_request.readyState == 4) {
	if (http_request.status == 200) {

	document.all['shippingHtml'].innerHTML=http_request.responseText;
	} else {

	}
	}
}

function addProductsToCart(productId,count,clothes_size,clothes_color,action){

	if (document.all["prod_count_"+productId]){
		count= (document.all["prod_count_"+productId].value);
	}

	if (productId > 0) {
		if (count == '' || count == 0)
		      return alert('Кол-во товара не может быть равным 0');
		if (count > 50)
		      return alert('Вы оптовый покупатель? Свяжитесь с нами, мы все обсудим!');

	 
		  if (isNaN(count))
		      return alert('Кол-во товаров должно быть только числовым');
	 
	//	  if (count <= 0)
	//	      return alert('Кол-во товаров не может быть меньше нуля');

		var clothes_colors='clothes_colors_' + productId;

		if (document.all[clothes_colors]){
			var objSelColors = document.all[clothes_colors];
			var clothes_color = objSelColors.options[objSelColors.selectedIndex].value;
		}

		var clothes_sizes='clothes_sizes_' + productId;
		if (document.all[clothes_sizes]){
			var objSelSizes = document.all[clothes_sizes];
			var clothes_size = objSelSizes.options[objSelSizes.selectedIndex].value;
		}

		if (!clothes_size){
			clothes_size='Any';
		}

		if (!clothes_color){
			clothes_color='Any';
		}

	//alert(color);
	}//action
	if (!productId || !count){
		 queryString='';
	} else {
		 queryString='productId=' + productId + "&count=" + count + "&clothes_size=" + clothes_size + "&clothes_color=" + clothes_color ;
	}
	
	makeAjaxRequest('http://' + window.location.toString().split("//")[1].split("/")[0] + '/addProductsToCart.php?'+queryString);

	if (action){
		window.location='showCart.php'
	} else {
		return false;	
	}

}

function reCalcProductCount(productId, action,product_price,clothes_size,clothes_color){

fieldName='shopCartProductId_' +productId + "_" + clothes_size + "_" + clothes_color;
if (document.all[fieldName]){
	prodCount='productCount_' + productId  + "_" + clothes_size + "_" + clothes_color;
	prodPrice='product_price_' + productId  + "_" + clothes_size + "_" + clothes_color;
	product_price_final='product_price_final_'+ productId + "_" + clothes_size + "_" + clothes_color;

//Было	curValue=document.all[fieldName].value;
	curValue=document.all[fieldName].innerHTML;

	curValue=parseInt(curValue);

	if (curValue==1 && action==-1){
		var cont = confirm('Вы пытаетесь удалить товар из Вашей корзины. Нажмите ОК, если Вы действительно хотите его удалить, или ОТМЕНА, если Вы хотите оставить товар в Вашей корзине');
		if (!cont){
			addProductsToCart(productId,1,clothes_size,clothes_color,action);
			window.location.location("/showCart.php");
//			window.location.reload();
			return false;	
		}
	}


	prod_price=parseInt(document.all[prodPrice].innerHTML);

	var allPrice=parseInt(document.all['allPrice'].innerHTML);

	newValue=curValue+action;

	if (newValue ==20 && action!=-1)
	      alert('Вы оптовый покупатель? Свяжитесь с нами, мы все обсудим!');

	if (newValue==0){
		window.location.href="/showCart.php";
//		window.location.reload();
		newValue=0;
	}else{
	       	allPrice+=(prod_price)*action;
	}
//Было	document.all[fieldName].value=newValue;//вывели кол-во товара в текстовое поле
	document.all[fieldName].innerHTML=newValue;//вывели кол-во товара в текстовое поле


	document.all[prodCount].innerHTML=newValue;//вывели кол-во товара
	document.all[product_price_final].innerHTML=prod_price*newValue;//вывели сумму*кол-во конкретного товара

	document.all['allPrice'].innerHTML=allPrice;
        makeAjaxRequestS('http://' + window.location.toString().split("//")[1].split("/")[0] + '/getShippingMethod.php?orderSum='+allPrice + '&$shippingMethod=');

	return false;
}


}
function delProductsFromCart(productId,count,clothes_size,clothes_color){

 queryString='productId=' + productId + "&count=" + count + "&clothes_size=" + clothes_size + "&clothes_color=" + clothes_color ;
 makeAjaxRequest('http://' + window.location.toString().split("//")[1].split("/")[0] + '/delProductsFromCart.php?'+queryString);

}

function showTime(){
	var a = new Date();
	document.write(a);
	document.write(" Ms:"+a.getMilliseconds());
}

function addBookmark(url, title)
{
  if (!url) url = location.href;
  if (!title) title = document.title;

  //Gecko
  if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
  //IE4+
  else if (typeof window.external == "object") window.external.AddFavorite(url, title);
  //Opera7+
  else if (window.opera && document.createElement)
  {
    var a = document.createElement('A');
    if (!a) return false; //IF Opera 6
    a.setAttribute('rel','sidebar');
    a.setAttribute('href',url);
    a.setAttribute('title',title);
    a.click();
  }
  else return false;

  return true;
}

function showFoto(imgSrc){
//alert(imgSrc);
//	eval(document['productPicture'].src = imgSrc); 
	document.all['productPicture'].src = imgSrc; 




}

function Delete_Cookie( name, path, domain ) {
return;
//alert(name);



document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	showCart();
}
function clearCart(){
	 makeAjaxRequest('http://' + window.location.toString().split("//")[1].split("/")[0] + '/clearCart.php');

return;
	var c_start=document.cookie;
	var products=(c_start.split(";"));
	i=0;
	while(i<products.length){
		cookieName=(products[i].split("="));
		var onlyProdStr=cookieName[0];
		if (onlyProdStr.indexOf("prod_id")>=0){
			Delete_Cookie(cookieName[0],'/','');
		}		
		i++;
	}

}



function showCart(cartProductsCount){
if (document.getElementById("cartCount")){
	document.getElementById("cartCount").innerHTML="0";

var j=0;
var cartLength=0;

cartLength=cartProductsCount;
//alert(location.href);

//if (parseInt(cartLength) > 0 && !document.all['scok'] && location.href.indexOf("showCart.php")>0){
//		window.location.reload();
//}
		if(cartLength>0) {
			document.getElementById("cartCount").innerHTML=cartLength;
			if(document.getElementById('cartImage').src != "/images/shopping-cart-full.png") {
				document.getElementById('cartImage').src = "/images/shopping-cart-full.png"; 
			}
		} else {
			document.getElementById("cartCount").innerHTML="0";
			document.getElementById('cartImage').src = "images/shopping-cart-empty.png"; 
		}
	}
//}//if

}
function randomnumber(){
	var randomnumber=Math.floor(Math.random()*100000);
	return randomnumber;
	}
	
function setCookie (name, value, expires, path, domain, secure) {

//alert(value);
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
	
//alert ("Мы положили, для Вас, выбранный товар в корзину. ");
var cont = confirm('Мы положили, для Вас, выбранный товар в корзину.\n Если Вы хотите сейчас оформить заказ, то нажмите ОК, а если хотите продолжить выбор, то нажмите Отмена');
if (cont){
	window.location='showCart.php'
}


//showCart();

}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);

}



function openWindowPodarok(width,height,TheUrl){

window.open(TheUrl, 'popup', 'height=' + height + ',width=' + width + ',status=no,toolbar=no,menubar=no,location=no,scrollbars=0')
}

