function indexSlider(id, direction){
   $('#'+id).jcarousel(direction);
   return false;
}

// JavaScript Document

//=====================================================================================
function prepareMouseOverImage(image, originalURL)
{
	image.mouseOverImage=originalURL;
	image.onload=function(){return true;};

	if($.browser.msie){
		image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
	} 
	else
	{
		image.src=grayscale(image, false);
	}
}

function grayscale(image, bPlaceImage)
{
  var myCanvas=document.createElement("canvas");
  var myCanvasContext=myCanvas.getContext("2d");

  var imgWidth=image.width;
  var imgHeight=image.height;
  // You'll get some string error if you fail to specify the dimensions
  myCanvas.width= imgWidth;
  myCanvas.height=imgHeight;
//  alert(imgWidth);
  myCanvasContext.drawImage(image,0,0);

  // The getImageData() function cannot be called if the image is not from the same domain.
  // You'll get security error
  var imageData=myCanvasContext.getImageData(0,0, imgWidth, imgHeight);
  for (i=0; i<imageData.height; i++)
  {
    for (j=0; j<imageData.width; j++)
    {
	  var index=(i*4)*imageData.width+(j*4);
	  var red=imageData.data[index];
	  var green=imageData.data[index+1];
	  var blue=imageData.data[index+2];
	  var alpha=imageData.data[index+3];
	  var average=(red+green+blue)/3;
   	  imageData.data[index]=average;
   	  imageData.data[index+1]=average;
   	  imageData.data[index+2]=average;
   	  imageData.data[index+3]=alpha;
	}
  }
  myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);
 // myCanvasContext.drawIMage(imageData,0,0);//,0,0, imageData.width, imageData.height);

  if (bPlaceImage)
  {
	  var myDiv=document.createElement("div");
	  myDiv.appendChild(myCanvas);
	  image.parentNode.appendChild(myCanvas);//, image);
  }
  return myCanvas.toDataURL();
}
//=====================================================================================

var addPngFixClass = function() {

	$('ul.typeCars li a').addClass('pngfix');
	
	$('ul.typeCars li a').hover(function() {
		$(this).addClass('pngfix');
	}, function(){
		$(this).removeClass('pngfix');
	});		
}
//=====================================================================================

var changeBackgrProdList = function() {
	$('ul.listProd li').hover(function() {
		$(this).find('.infoProd').css("background-color", "#f40000");
		$(this).find('.priceProd').css("color", "#fcb8b8");
		$(this).find('.txtProd p').css("color", "#fbb8b8");
	}, function(){
		$(this).find('.infoProd').css("background-color", "#161616");
		$(this).find('.priceProd').css("color", "#bd1010");
		$(this).find('.txtProd p').css("color", "#bebebe");
	});		
}

//                       set car types (categories) and seasons.
//=====================================================================================

$(function() {
   $('ul.typeCars li').click(function() {
      $(this).parent().children('li').removeClass('actTypeCar pngfix');
      $(this).addClass('actTypeCar pngfix');
   });
});

$(function() {
   $('ul.typeTyres li').click(function() {
      $(this).parent().children('li').removeClass('activeRd');
      $(this).addClass('activeRd');
   });
});

//=====================================================================================

var viewSubMenu = function() {

	$('.mainNav li').hover(function() {
		$(this).addClass('hoverLi');
		$('#'+$(this).find('.subMenu').attr('id')).show();
	}, function(){
		$(this).removeClass('hoverLi');
		$(this).find('.subMenu').hide();
	});	
}
//=====================================================================================

var viewRegBox = function() {

	$('.btnVhod').bind('click', function() {

		var topPosition = -193, animationSpeed = 1000;
		
		if(parseInt($('#logIn').css('top')) === topPosition) {
			$('#logIn').animate({
				top : 0
			}, animationSpeed);
		} else {
			$('#logIn').animate({
				top : topPosition
			}, animationSpeed);
		}
	});
}

//=====================================================================================
var viewFloatBasket = function() {

	$('.basketBtn').bind('click', function() {

		var rightPosition = -98, animationSpeed = 600;
		
		if(parseInt($('.basketBox').css('right')) === rightPosition) {
			$('.basketBox').animate({
				right : 0
				
			}, animationSpeed);
		} else {
			$('.basketBox').animate({
				right : rightPosition
			}, animationSpeed);
		}
	});
}
//=====================================================================================

var changeClassPromotionList = function() {
   var elements = $('.listPromotions li');
   $('ul.listPromotions li').hover(function() {
      $(this).find('a.thumbImgPromo').parent().addClass('active');
   }, function(){
      if( ($(this).find('a.thumbImgPromo').parent().attr('id')) != (elements[selectedImg].id) ){
         $(this).find('a.thumbImgPromo').parent().removeClass('active');
      }
   });
}

function setCurrentManufacturer(obj){
   var id;
   if(obj.id) { id = obj.id.replace('man_', '');
   } else {
   id = this.id.replace('man_', '');
   }
   $('#selectedManufacturer').html($('#man_'+id).html());
   $('#manufacturerId').attr('value', id);
   $('#manufacturersList').hide();
   setFilterParams();
}

function setCurrentWidth(obj){
   var id;
   if(obj.id) { id = obj.id.replace('w_', '');
   } else {
      id = this.id.replace('w_', '');
   }
   $('#selectedWidth').html($('#w_'+id).html());
   $('#productWidth').attr('value', id);
   $('#widthList').hide();
   setFilterParams();
}
function setCurrentHeight(obj){
   var id;
   if(obj.id) { id = obj.id.replace('h_', '');
   } else {
      id = this.id.replace('h_', '');
   }
   $('#selectedHeight').html($('#h_'+id).html());
   $('#productHeight').attr('value', id);
   $('#heightList').hide();
   setFilterParams();
}
function setCurrentDiameter(obj){
   var id;
   if(obj.id) { id = obj.id.replace('d_', '');
   } else {
      id = this.id.replace('d_', '');
   }
   $('#selectedDiameter').html($('#d_'+id).html());
   $('#productDiameter').attr('value', id);
   $('#diameterList').hide();
   setFilterParams();
}

function setFilterParams(){
   var title, categoryId, manufacturerId, seasonId, productPrice, productWidth, productHeight, productDiameter;
   var widthObj               = document.getElementById('widthList');
   var heightObj              = document.getElementById('heightList');
   var diameterObj            = document.getElementById('diameterList');
   var manufacturerObj        = document.getElementById('manufacturersList');
   var jspWidth               = $(widthObj).find('.jspPane');
   var jspHeight              = $(heightObj).find('.jspPane');
   var jspDiameter            = $(diameterObj).find('.jspPane');
   var jspManufacturer        = $(manufacturerObj).find('.jspPane');
   if(jspWidth.size() > 0){
      widthObj = jspWidth.get(0);
   }
   if(jspHeight.size() > 0){
      heightObj = jspHeight.get(0);
   }
   if(jspDiameter.size() > 0){
      diameterObj = jspDiameter.get(0);
   }
   if(jspManufacturer.size() > 0){
      manufacturerObj = jspManufacturer.get(0);
   }
   widthObj.innerHTML         = '';
   heightObj.innerHTML        = '';
   diameterObj.innerHTML      = '';
   manufacturerObj.innerHTML  = '';
   categoryId        = $('#categoryId').attr('value');
   manufacturerId    = $('#manufacturerId').attr('value');
   seasonId          = $('#seasonId').attr('value');
   productPrice      = $('#productPrice').attr('value');
   productWidth      = $('#productWidth').attr('value');
   productHeight     = $('#productHeight').attr('value');
   productDiameter   = $('#productDiameter').attr('value');
   $.ajax({
//      url: '/shop/?action=' + action +
      url: '/shop/?action=setFilterParams' +
      '&categoryId='        + categoryId +
      '&manufacturerId='    + manufacturerId +
      '&seasongId='         + seasonId +
      '&productPrice='      + productPrice +
      '&productWidth='      + productWidth +
      '&productHeight='     + productHeight +
      '&productDiameter='   + productDiameter +
      '&plugins=disable',
      type: 'POST',
      dataType: 'json',
      async: false,
      success: function(json){
         if (json['man']) {
            for(var i = 0; i < json['man'].length; i++){
               var id    = json['man'][i]['id'];
               title = json['man'][i]['title'];
               var objLi   = document.createElement('li');
               objLi.id    = id;
               var objLink = document.createElement('a');
               objLink.className    = 'listManufacturers';
               objLink.id           = 'man_' + id;
               objLink.innerHTML    = title;
               objLi.appendChild(objLink);
               manufacturerObj.appendChild(objLi);
//               objLink.href = "javascript:setCurrentManufacturer("+id+");";
//               objLink.addEventListener('click', setCurrentManufacturer, true);
			   objLink.onclick = function() {setCurrentManufacturer(this)};
            }
         }
         var objLi   = document.createElement('li');
         var objLink = document.createElement('a');
         objLink.innerHTML    = 'избери';
         objLink.id           = 'w_';
         objLi.appendChild(objLink);
         widthObj.appendChild(objLi);
         //objLink.addEventListener('click', setCurrentWidth, true);
		 objLink.onclick = function(){setCurrentWidth(this)};
         if(json['filterWidth']){
            for(var i = 0; i < json['filterWidth'].length; i++){
               var objLi   = document.createElement('li');
               var objLink = document.createElement('a');
               objLink.innerHTML    = json['filterWidth'][i]['size'];
               objLink.id           = 'w_'+json['filterWidth'][i]['size'];
               objLi.appendChild(objLink);
               widthObj.appendChild(objLi);
               //objLink.addEventListener('click', setCurrentWidth, true);
			   objLink.onclick = function(){setCurrentWidth(this)};
            }
         }
         var objLi   = document.createElement('li');
         var objLink = document.createElement('a');
         objLink.innerHTML    = 'избери';
         objLink.id           = 'h_';
         objLi.appendChild(objLink);
         heightObj.appendChild(objLi);
         //objLink.addEventListener('click', setCurrentHeight, true);
		 objLink.onclick = function() {setCurrentHeight(this)};
         if(json['filterHeight']){
            for(var i = 0; i < json['filterHeight'].length; i++){
               var objLi   = document.createElement('li');
               var objLink = document.createElement('a');
               objLink.innerHTML    = json['filterHeight'][i]['size'];
               objLink.id           = 'h_'+json['filterHeight'][i]['size'];
               objLi.appendChild(objLink);
               heightObj.appendChild(objLi);
               //objLink.addEventListener('click', setCurrentHeight, true);
			   objLink.onclick = function(){setCurrentHeight(this)};
            }
         }
         var objLi   = document.createElement('li');
         var objLink = document.createElement('a');
         objLink.innerHTML    = 'избери';
         objLink.id           = 'd_';
         objLi.appendChild(objLink);
         diameterObj.appendChild(objLi);
         //objLink.addEventListener('click', setCurrentDiameter, true);
		 objLink.onclick = function(){setCurrentDiameter(this)};
         if(json['filterDiameter']){
            for(var i = 0; i < json['filterDiameter'].length; i++){
               var objLi   = document.createElement('li');
               var objLink = document.createElement('a');
               objLink.innerHTML    = json['filterDiameter'][i]['size'];
               objLink.id           = 'd_'+json['filterDiameter'][i]['size'];
               objLi.appendChild(objLink);
               diameterObj.appendChild(objLi);
               //objLink.addEventListener('click', setCurrentDiameter, true);
			   objLink.onclick = function(){setCurrentDiameter(this)};
            }
         }
      }
   });
}

var SliderEnabled = true;
var func = 'slideNext()';
//var direction = 'right';
var visibleElements = 4;
var selectedImg = 0;
var selectedPosition = 0;
var firstVisible  = 0;
var lastVisible   = visibleElements - 1;
var moving2 = false;
var gr = 124;
var rand_pos;
var rand_count = 0;
var rand_pixels = 10;
var manual = false;
var eCount;
var active = true;

function setPromotion(id, sldImg, promoUrl, eStatus){
   if(eStatus == 'click'){
      SliderEnabled = false;
      selectedImg = sldImg - 1;
   }

   $('ul.listPromotions li').removeClass('active');
   $('#'+id).parent().parent().addClass('active');

   var title, img;
   //var objPromId  = $('#promId');
   var objTitle   = $('#promTitle');
   //var objDesc    = $('#promDesc');
   //var objValue   = $('#promValue');
   var objImg     = $('#promImg');
   $.ajax({
      url: '?action=setAccent&accentId=' + id + '&plugins=disable',
      type: 'POST',
      dataType: 'json',
      async: false,
      success: function(json){
         if (json['accent']) {
            promId      = json['accent']['id'];
            url         = json['accent']['url'];
            title       = json['accent']['title'];
            desc        = json['accent']['desc'];
            value       = json['accent']['value'];
            img         = json['accent']['img'];
         }
      }
   });
   objTitle.html(title);
   if(eStatus == 'def'){
      objImg.attr('src', img);
   } else {
      objImg.fadeOut(300, function() {
         objImg.attr('src', img);
      });
      objImg.fadeIn(300);
   }
   if(!promoUrl && url){
      promoUrl = url;
   }
   document.getElementById('promoUrlTitle').href=promoUrl;
   document.getElementById('promoUrlImg').href=promoUrl;
   document.getElementById('promoUrlSeeMore').href=promoUrl;

}

function stopInterval(intId){
   clearInterval(intId);
}

var autoSliding = function() {
   if(SliderEnabled){
      var timer = 4000;
      active = true;
      if(!manual){
         setTimeout(function(){sliderAnimation(null, null)}, timer);
      }
   }
//   else {
//      manual = false;
//   }
}

var setSelectedImg = function(id) {
   setPromotion(id);
//   $('.listPromotions li').removeClass('active');
//   $('#'+id).parent().parent().addClass('active');
}

function changeButtonStatus(button, action){
   if(button == 'leftButton'){
      if(action == 'on'){
         $('#'+button).removeClass('prevPromoOff');
         $('#'+button).addClass('prevPromoOn');
      } else {
         $('#'+button).removeClass('prevPromoOn');
         $('#'+button).addClass('prevPromoOff');
      }
   } else {
      if(action == 'on'){
         $('#'+button).removeClass('nextPromoOff');
         $('#'+button).addClass('nextPromoOn');
      } else {
         $('#'+button).removeClass('nextPromoOn');
         $('#'+button).addClass('nextPromoOff');
      }
   }
}

function slidePrev(){

   var ulc = document.getElementById("promotionsList");
   var current_pos = ulc.style.left;
   rand_pos = gr;
   if( parseInt(current_pos) == 0 ){ return false }
   rand_move();
   return true;
}

function slideNext(){

   var ulc = document.getElementById("promotionsList");
   var current_pos = ulc.style.left;
   var end = document.getElementById("eCount").value;
   if( end -4 == selectedImg ){ return false }
   rand_pos = -gr;
   rand_move();
   return true;
}

function rand_move(){
   var sign = rand_pos > 1 ? rand_pixels : -rand_pixels ;
   var ulc;
   var timer; 
   ulc = document.getElementById("promotionsList");
   var cur_pos = ulc.style.left;
   cur_pos = parseInt(cur_pos);
   var posi = (cur_pos + sign );
   ulc.style.left = posi+'px'; 
   rand_pos  = rand_pos-sign ;

   if( parseInt(rand_pos/rand_pixels) == 0 ){
           ulc.style.left = parseInt(ulc.style.left)+rand_pos+'px';
           rand_pos = 0;
   }
       if( rand_pos != 0 ){
       timer = setTimeout(function(){ rand_move();return true; }, 50);
       moving2 = true;
       active = false;
   }else{
       clearTimeout(timer);
       active = true;
       moving2 = false;
   }
}

function sliderAnimation(clickDir, eStatus){
   if(!SliderEnabled && !eStatus){ return 0; }
   if(active){ 
      active = false;

      if(clickDir != null){
         func = clickDir;
         manual = true;
      }
      var elements = new Array();
      var images = document.getElementsByTagName("img");
      for(k=0;k<=images.length;k++){
         if(images[k] && images[k].className.search(/^promoImages$/) != -1 ){
            elements.push(images[k]);
         }
      }
      eCount = elements.length;

      if(func == 'slideNext()'){
         if(selectedImg < (eCount - 1)){
            selectedImg++;
            setSelectedImg(elements[selectedImg].id);
            if(firstVisible + visibleElements == selectedImg){
               firstVisible++;
               lastVisible++;
               eval(func);
            }
         } else {
            func = 'slidePrev()';
         }
      } else {
         if(selectedImg != 0){
            selectedImg--;
            setSelectedImg(elements[selectedImg].id);
            if(lastVisible - visibleElements == selectedImg){
               lastVisible--;
               firstVisible--;
               eval(func);
            }
         } else {
            func = 'slideNext()';
         }  
      }
      if(firstVisible > 0){
         // set left arrow on
         changeButtonStatus('leftButton', 'on'); 
      } else { // set off 
         changeButtonStatus('leftButton', 'off');
      }
      if(lastVisible < (eCount - 1)){
         // set right arrow on
         changeButtonStatus('rightButton', 'on'); 
      } else { // set off 
         changeButtonStatus('rightButton', 'off'); 
      }
   }
   active = true;
   autoSliding();
}

function getViewportSize() {
	
	var viewportwidth;
	var viewportheight;

	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth	= window.innerWidth,
		viewportheight	= window.innerHeight
	}

	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
	   viewportwidth	= document.documentElement.clientWidth,
	   viewportheight	= document.documentElement.clientHeight
	}

	// older versions of IE
	else
	{
	   viewportwidth	= document.getElementsByTagName('body')[0].clientWidth,
	   viewportheight	= document.getElementsByTagName('body')[0].clientHeight
	}
	
	return {width:viewportwidth,height:viewportheight}
}

