$(document).ready(function () {
	//to do not execute this script as much as it's called...
  makeTransparentLink('.banner-priemka', '/shop/about.php?id=7');
  makeTransparentLink('.main-icon-moto', '/p0_k.htm');
  makeTransparentLink('.main-icon-avto', '/p0_a.htm');
  makeTransparentLink('.main-icon-zaryadka', '/p0_n.htm');
  makeTransparentLink('.head-top-logo', '/');
  makeTransparentLink('.indentBasket', '/basket/');
  makeTransparentLink('.YandexMoneyLogo', '/shop/about.php?id=2');
  makeAlink();
  makeAlinkPreview();


  if(!$('ul.menu-groups').hasClass('dynamized'))
	{
    // скроем все менюшки
    $('div.menuContainer ul li').hide();
    
    // Откроем активную группу
    if($('div.menuContainer a').is('.selected'))
    {

      $('div.menuContainer a.selected').parents().show();
      // откроем наследников активной группы

      $('div.menuContainer a.selected').parent().children().children().show();
  		$('ul.menu-groups .selected').parent().each( function() {
  			if ($(this).is('li'))
  				$(this).prevAll().show();
  			$(this).nextAll().show();
  		});

      $('ul.menu-groups .selected').parent().parent().each( function() {
  			if ($(this).is('li'))
  				$(this).prevAll().show();
  			$(this).nextAll().show();
  		});
      $('ul.menu-groups .selected').parent().parent().parent().each( function() {
  			if ($(this).is('li'))
  				$(this).prevAll().show();
  			$(this).nextAll().show();
  		});

    }
    else
    {

      $('div.menuContainer>ul>li').show();
    }

	}

  //$('body').nivoZoom();
  /*
  $('body').nivoZoom({
		speed:300,
		zoomHoverOpacity:0.8,
		overlay:true,
		overlayColor:'#333',
		overlayOpacity:0.5,
		captionOpacity:0.8
	});
  */
  $('.podbor-row').mouseover(function(){
    $(this).css({
      backgroundColor: '#eeeeee'
    });
  });

  $('.podbor-row').mouseout(function(){
    $(this).css({
      backgroundColor: 'transparent'
    });
  });
  $('.ModificationTable tr').mouseover(function(){
    $(this).css({
      backgroundColor: '#eeeeee'
    });
  });

  $('.ModificationTable tr').mouseout(function(){
    $(this).css({
      backgroundColor: 'transparent'
    });
  });

  jQuery(function()
  {
  	jQuery('#paneVendors').jScrollPane({scrollbarWidth:15, showArrows:true, animateTo: true, animateInterval: 50, animateStep: 4});
    jQuery('#paneModels').jScrollPane({scrollbarWidth:15, showArrows:true,animateTo: true, animateInterval: 50, animateStep: 4});

    if(typeof scrollToVendors !=="undefined")
    {
      if(scrollToVendors.nameRow!='')
        specScrollMoveTo('#'+scrollToVendors.idBlock, '#vendorRow'+scrollToVendors.nameRow);
      if(scrollToModels.nameRow!='')
        specScrollMoveTo('#'+scrollToModels.idBlock, '#modelRow'+scrollToModels.nameRow);
    }
  });
  var colour = $("div#overlay");
	var content = $("#CommentsForm");

	content.hide();
	colour.hide();

  /*
  $(window).scroll(function(){
    if(content.css('display')=='block')
      content.css({top: $(window).scrollTop()+(content.height()/2)+'px'});
  });
  */
  $('#CommentsCancel').click(function(){
    content.hide();
    colour.stop().fadeTo(100, 0, function(){
      colour.css({display: 'none'});
    })
    return false;
  })
  $('#CommentsFormSubmit').click(function(){
    // готовим объект
    var options = {
      target: "#CommentsContent",
      url: "/shop/meClick.php",
      success: function() {
        $('#CommentsCancel').click();
        commentBlick();
        return false;
      }
    };
    // передаем опции в  ajaxSubmit
    $("#CommentsFormForm").ajaxSubmit(options);
    return false;
  })

  $('.buttonBuy').mouseover(function(){
    buttonBuyAnimate();
  })
  $('.CommentsAdd').click(function(){

    $('#CommentsForm').css({
      display: 'block',
      visibility: 'visible',
      position: 'absolute'

    });


    // Определим видимую часть экрана
    var scrollTop       = $(window).scrollTop();
    var scrollLeft      = $(window).scrollLeft();
    var contentWidth    = content.width();
    var contentHeight   = content.height();
    var windowWidth     = $(document).width();
    var windowHeight    = $(document).height();
    $('div#overlay').css({
      display: 'block',
      visibility: 'visible',
      position: 'absolute',
      width:  windowWidth+scrollLeft+'px',
      height: windowHeight+'px'

    });


    content.stop().show().css({ "left" : "-"+contentWidth+"px"}).animate({left : (windowWidth-contentWidth)/2+'px', top: scrollTop+(contentHeight/2)+'px'}, 300);
		colour.stop().fadeTo(500, .4)


    return false;
  })
   makeButtonsTransparentLink();
});
function makeAlink()
{

  $(".PlaceHolderMakeAlink").each(function(){
    id  = $(this).attr('id');
    $.getJSON('/adv/get/?goodsspr_id='+id + '&short=1',function(json)
    {
      for(key in json)
      {
        $('#'+key).html(json[key]);
      }

      return;
    });
  });
}
function makeAlinkPreview()
{
  $(".w_b_a_link").each(function(){
    var prevID  = $(this).attr('prev_atr');

    $(this).click(function(pos){
      //alert('узнать цену?');
      var container = makePrevBlock(pos);
      //return false;
      
      $.getJSON('/adv/get/?goodsspr_id='+prevID + '&short=1',function(json)
      {
        $(container).html(
          "<h3><a href='/goodsspr/"+prevID+"/model.htm'>"+json.goods_name+"</a></h3>"+
          "<img src='/shop/images/gsimg_small/"+prevID+".jpg' /><br />"+
          json[prevID]
        );
        /*
        for(key in json)
        {
          $('#'+key).html(json[key]);
        }
        */
        
      });
      return false;
    });


  });
}
function makePrevBlock(pos)
{
  var div = document.createElement("DIV");
  $(div).attr({'class':'short-place-holder-prev'});
  
  w_size  = getWindowSize();
  $(div).css({'width':' 400px','height':'200px','position':'absolute','top':'400px','left': '400px'});
  if(w_size.clientWidth>pos.pageX-20+400)
    $(div).css({'top': pos.pageY-10,'left': pos.pageX-20});
  else
    $(div).css({'top': pos.pageY-10,'left': w_size.clientWidth-450});
    
  $(div).appendTo("body");
  //$(div).show();
  $(div).fadeTo(100, 1,function(){
    //$(div).fadeTo(100, 1)
  });
  $(div).mouseleave(function(){
    $(div).fadeOut(1000,function(){
      $(div).remove();
    });
  })
  return div;
}
function getWindowSize()
{
  var clientWidth   = $(window).width();
  var clientHeight  = $(window).height();
  var scroll        = $(window).scrollTop();
  var docHeight     = $(document).height();
  var docWidth      = $(document).width();
  return ({'clientWidth': clientWidth, 'clientHeight': clientHeight, 'scroll': scroll, 'docWidth': docWidth, 'docHeight': docHeight});
}

function commentBlick()
{
  $('#commentBlick').fadeTo(100, .1,function(){
    $('#commentBlick').fadeTo(100, 1)
  });

}
function buttonBuyAnimate()
{
  /*
  $('.buttonBuy').fadeTo(100, .4,function(){
    $('.buttonBuy').fadeTo(100, 1)
  });
  */
}
function basketAddAnimate(Obj)
{
  var goodsspr_id = Obj.attr('g_id');
  var imageContainer  = $('#goodsImage_'+goodsspr_id).find('.image-tumb-cell-img img');     //alert(imageContainer.text());
  if(imageContainer.length==0)
  {
    //alert('noFoundContainer id='+goodsspr_id);
    return;
  }


  var width       = imageContainer.width();
  var height      = imageContainer.height();
  var scrollTop   =  imageContainer.scrollTop();
  var scrollLeft  =  imageContainer.scrollLeft();
  var top         =  imageContainer.offset().top;
  var left        =  imageContainer.offset().left;



  var myDiv = $('<img>');

  myDiv.css({
    position: 'absolute',
    top: top,
    left: left,
    border: '1px red solid',
    visibility: 'visible',
    width: width+'px',
    height: height+'px'
  });


  myDiv.attr('src',imageContainer.attr('src'));
  /*
  myImg.attr('src',imageContainer.find('img').attr('src'));
  myImg.attr('height',height);
  myImg.attr('width',width);
  
  myImg.appendTo(myDiv);
  */
  myDiv.appendTo("body");

  var dest={
    x: $('#basketIcon').offset().left,
    y: $('#basketIcon').offset().top,
    width: $('#basketIcon').width(),
    height: $('#basketIcon').height()
  };

  myDiv.animate({
    left: dest.x, top: dest.y,width: dest.width, height: dest.height
  }, 1800, "", function(){
    $(this).hide();
  });


}

function makeButtonsTransparentLink()
{
  $('.buttonBuy').each(function(){
    var parentContainer = $(this);
    var aObj  = $('a',this);
    //alert(aObj);
    var href  = aObj.attr('href');  //alert(href);
    //makeTransparentLink(this, href+'&ajax=1');
    $(aObj).click(function(){
      
      $.ajax({
        type: 'GET',
        url: href+'&ajax=1',
        dataType : "json",
        cache:  false,
        success: function (data, textStatus) {
          $('.indentBasket span').html(data.short_info); //alert(data.short_info);
          basketAddAnimate(parentContainer);
          
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          //alert("TECHNICAL ERROR: unable to refresh the cart.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
        }
      });
      return false;
    });
  })
}
function makeTransparentLink(idContainer, link)
{
  if($(idContainer).length==0) return;

  var width       = $(idContainer).width();
  var height      = $(idContainer).height();
  var scrollLeft  = $(idContainer).scrollLeft();
  var scrollTop   = $(idContainer).scrollTop();

  var offsetTop = $(idContainer).offset().top;
  var offsetLeft = $(idContainer).offset().left;
  //alert(width + ':' + height + ':'+scrollLeft+':' + scrollTop+ ':'+ $(idContainer).offset().top);

  var myImage = $('<img>');
  myImage.css({
    position: 'absolute',
    top: offsetTop,
    left: offsetLeft,
    border: '0px black solid',
    visibility: 'visible'
  });
  myImage.attr("src",'/images/1x1.gif');
  myImage.attr("width",   width);
  myImage.attr("height",  height);


  myLink  = $('<a>');
  myLink.attr("href",link);
  

  myImage.appendTo(myLink);
  myLink.appendTo("body");
}
function testPanel()
{
  if(scrollToVendors.nameRow!='')
      specScrollMoveTo(scrollToVendors.idBlock, 'vendorRow'+scrollToVendors.nameRow);
}
function specScrollMoveTo(idScroll, idRow)
{
  if(idRow!='')
  {
    jQuery(idScroll)[0].scrollTo(idRow);
    $(idRow+' a').css({color: 'Red'});
  }
}



