function OnMMCur() {
 var cur;
 cur = document.getElementById("mm_cur");

 $(cur).mouseover( function() { $(cur).css("background","url('/imgs/mm_light_blue_bg.gif')");});
 $(cur).mouseout(  function() { $(cur).css("background","url('/imgs/mm_blue_bg.gif')");});
}

function strrev( string ) {
    var ret = '', i = 0;

    string += '';
    for ( i = string.length-1; i >= 0; i-- ){
       ret += string.charAt(i);
    }

    return ret;
}

jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

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() {

  $('#find')
    .keydown(function() {onEnterSearch(this,event)})
    .blur(function() {if(this.value=='') {this.value='поиск';}})
    .focus(function() {if(this.value=='поиск') this.value='';});

  $('#how_to_use_btn').click( function(){$('#how_to_use_text').toggle()});

  OnMMCur();

  $('.p-description').hide();

  $('#how_to_use_text').hide().css('position','relative');
  $('.add').hide();

  $('#cmail2').html(strrev('a'+'u'+'.'+'m'+'o'+'c'+'.'+'l'+'e'+'b'+'e'+'m'+'-'+'t'+'i'+'h'+'@'+'o'+'f'+'n'+'i'+':'+'o'+'t'+'l'+'i'+'a'+'m'));


  $("#ff-params-table").css("display","none");
  $('#ff-params-href').click(
       function () {
         $("#ff-params-table").toggle("fast");} );

  $("#ff-add-params-table").css("display","none");
  $('#ff-add-params-href').click(
       function () {
         $("#ff-add-params-table").toggle("fast");} );


  $('div.katalog-index-map').each(
  function(i,v)
  {
    var div = $(v);
    if(div.children('ul').length==0)
      div.children('a').css("text-decoration","underline");
  } );

  $('#lcolumn-visited-goods').load('/ajax/visited_goods.php');

  $('#actions').mouseover( function () { $(this).attr('src','/imgs/mm_actions_on.gif');});
  $('#actions').mouseout( function () { $(this).attr('src','/imgs/mm_actions.gif');});

  $('.checkbox span').addClass("pointer");
  $('.checkbox span').click(
     function() {
       $(this).parent().find('input').click();
     });

  $('div.checkbox input[name="col1"]').parent().attr("title","в подбор попадут модели с тёмными цветами и модели, у которых есть как тёмные так и светлые варианты на выбор").tooltip({track: true, delay: 0});

  $('div.checkbox input[name="col2"]').parent().attr("title","в подбор попадут модели со светлыми цветами и модели, у которых есть как тёмные так и светлые варианты на выбор").tooltip({track: true, delay: 0});

  $('td.good-photos-td img').each(
  function(i,v)
  {
    var theElement = $(v);
    theElement.click(
      function() {
        if($(this).className != 'cur')
        {
          path = theElement.attr("src");
          path = path.replace('_60x50','_540x720');

          var good_div = theElement.parent().parent().parent().parent().parent().parent();
          var offset = good_div.offset();

          $('html, body').animate({scrollTop: offset.top+'px'}, 500);

          good_div.find(".good-main-img").attr("src",path);
          theElement.parent().parent().find("img").attr("class","");
          theElement.attr("class","cur");
        }
      }
    );
    theElement.tooltip({
         track: true,
         delay: 0
        });

  } );


  $('img.good-main-img').each(
  function(i,v)
  {
    var theElement = $(v);
    theElement.tooltip({
         track: true,
         delay: 0
        });

  } );

  $('#filter-form input:checkbox').each(
    function(i,v) {
    var theElement = $(v);
    var name = theElement.get(0).name;
    if(name.substr(0,1)!='p') {
      theElement.attr("disabled","true");
      theElement.click(function(){ alert('Извините, но этот параметр пока недоступен для подбора');});
    }

  } );


  var w, content_width;
  content_width = $('#content').width();
  if(content_width > 552 && content_width < 670)
  {
    w = 10 + (content_width - 552)/2;
    $('.space').css('width',w);
  }

  $('.go-button').mouseover( function() { $(this).attr('src','/imgs/where_to_buy_on.gif');} );
  $('.go-button').mouseout( function() { $(this).attr('src','/imgs/where_to_buy.gif');} );

  var visited_goods = GetCookie('hm_visited_goods');


  $('.mark-good').each( function (i,v) {
      id_str = $(v).attr('id');
      if(id_str!='')
      {
        if(visited_goods)
        {
         offset = visited_goods.indexOf(id_str);
         if (offset != -1) {
           $(v).text('отмечен').attr('class','');
         }
        }
      }
    }
  );

  $('#write-a-wish-form').hide();
  $('#write-a-wish').click( function () { $('#write-a-wish-form').toggle('fast');});

  var send_a_wish_el;
  send_a_wish_el = document.getElementById("send_a_wisth");
  if(send_a_wish_el)
    send_a_wish_el.disabled = true;

  $('#wish_text').keyup( CheckWish ).change( CheckWish );

  if(send_a_wish_el)
    document.getElementById("send_a_wisth").disabled = true;

  $('#send_a_wisth').click( function (){
  	  $.post(
  	    '/ajax/site_write_a_wish.php',
  	    { wish_text: $('#wish_text').val(), wish_person: $('#wish_person').val(), wish_mail: $('#wish_mail').val()},
  	      function () {
  	    	alert('Спасибо. Ваша жалоба или пожелание отправлено и будет обязательно принято во внимание.');
  	    	$('#wish_person').val("");
                $('#wish_mail').val("");
                $('#wish_text').val("");
                $('#write-a-wish').click();
  	      }
     );
     }
   );

   $('#page-indicator tr td').each( function(i,v) { $(v).click( function() { GoToPage(i); } ) } );
   
   
   // visited goods block with fixed position 
		var placeholder = $( "#lcolumn-visited-goods-placeholder" );
		var fixed_block = $( "#lcolumn-visited-goods" );
		var view = $( window );
		view.bind(
			"scroll resize",
			function(){
				var placeholderTop = placeholder.offset().top;
				var viewTop = view.scrollTop();
				if (
				 (viewTop > placeholderTop) &&
				 !fixed_block.is( ".lcolumn-visited-goods-fixed" )
				){
				 placeholder.height(
						    placeholder.height()
				 );
				 fixed_block.addClass( "lcolumn-visited-goods-fixed" );
				} else if (
				 (viewTop <= placeholderTop) &&
				 fixed_block.is( ".lcolumn-visited-goods-fixed" )
				 ){
				 placeholder.css( "height", "auto" );
				 fixed_block.removeClass( "lcolumn-visited-goods-fixed" );
				}
			}
		);	

   
   $( "#filter-form-p0" ).button();
   $( ".price-checkbox-format" ).buttonset();
});

function GoToPage(i)
{
  href = $('#page-nav-href-table td:eq('+i+') a').attr('href');
  if(href!=undefined)
    location.href = href;
}


function SetVisitedGood( el, cat_name, tovar_id)
{ 
  $.ajax( '/ajax/set_visited_good.php',
	     {
	  		data: { 'cat_name': escape(cat_name), 'tovar_id': tovar_id },
	  		success: function (data) {
	  					$(el).text('отмечен').attr('class','');
	  					$('#lcolumn-visited-goods').load('/ajax/visited_goods.php', {cache: false});
	  				 },
	  		cache: false
	     }
	);
}

function CheckWish() {
    if($('#wish_text').val()!='')
      document.getElementById("send_a_wisth").disabled = false;
    else
      document.getElementById("send_a_wisth").disabled = true;
}

function onEnterSearch(el,event)
{
  ecode = (event.keyCode ? event.keyCode : event.which ? event.which : null);
  if(ecode==13)
    Search();
}

function Search()
{
  el = document.getElementById("search");
  if(el.value!="") { find=el.value; if(find.length>=3) location.href="/search.html?find="+find; else alert("Введённое слово для поиска должно состоять из более чем двух букв");}
}
