$(function() {
  $(".gallery_page").scrollable();

  $('.cart_img,.cart_link a').live('click',function(){
    add_cart( $(this).parent().attr('rel') );

  } );

  $('.item_cart .del').live('click',function(){
    $.post( '/gallery/rem_from_cart/'+$(this).attr('id'),"",
      function( data ){
        //show_prepopup( data );
        if ( data=='0' ){
          $('.cart_frame').empty().html('<h2>Ваша корзина заказов пуста!</h2>');
          $('.top_cart').html( '<a href="/cart" >Корзина заказов</a> пуста' );
          window.location = '/cart';
        }else{
          $('.cart_summ span').html(data+'.- $');
          $.post( '/gallery/get_cart_count/',"",function(data){
            $('.top_cart').html( 'В <a href="/cart" >корзине</a> <span>'+data+'</span> '+declOfNum(data, ['работа','работы','работ']) );
          });
        }
      }
    ); //endpost
    $('#cart_'+$(this).attr('id')+'').remove();
  });

  $('.price_label').hide();
		$('.image_gallery').live( {
    mouseover: function() {
						$('.price_label').hide();
      $(this).find('.price_label').show();
    },
    mouseout: function() {
      $('.price_label').hide();
    }
		} );

  $("#form_cart").validate({
    rules: {
     cust_email: {
       required: true,
       email: true
     },
     cust_phone: {
       required: true,
       number: true
     }
   }
  });

  $('#showLogin').find('a').click( function(){
    $('#loginWindow').fadeIn(400);
   }
  );
  $('#loginWinClose').click( function(){
    $('#loginWindow').fadeOut(400);
   }
  );

  $('#loginWinApply').click( function(){
    //отправка запроса на авторизацию
    $('#loginform').submit();
    $('#loginWindow').fadeOut(400);
   }
  );
  $("#loginform").find( 'input[name="password"]' ).keypress(function(event) {
    if ( event.which == 13 ) {
      $('#loginWinApply').click();
    }
   });

  $('#logOut').click( function(){
    //отправка запроса на выход логина
    $('#logoutform').submit();
   }
  );
  $('#loginWindow').corner('round:10px'); 
  $('ul.rightMenu').each(function() {
    $(this).find('li').each(function(i) {
      $(this).click(function(){
        $(this).addClass('active').siblings().removeClass('active')
          .parents('div.section').find('ul.anonce').fadeOut(300).delay(300).end().find('ul.anonce:eq('+i+')').fadeIn(400);
        if ( $('.rightAdmPanel').length ) {
          $('.rightAdmPanel').attr( 'id', $(this).attr('id') );
        }
      });
    });
  });

  $('.sort_block a').live("click", function(ev) {
    $( set_sort( this.id, ev ) );
  });

});

function declOfNum(number, titles) {
    cases = [2, 0, 1, 1, 1, 2];
    return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
}

function add_cart( id ){
  $.post( '/gallery/add_to_cart/'+id,"",
    function( data ){
      show_prepopup( data );
      $.post( '/gallery/get_cart_count/',"",function(data){
								//после добавления в корхзину надо отобразить это всё
								if ( data=='0' ){
          $('.top_cart').html( '<a href="/cart" >Корзина заказов</a> пуста' );
								}else{
          $('.top_cart').html( 'В <a href="/cart" >корзине</a> <span>'+data+'</span> '+declOfNum(data, ['работа','работы','работ']) );
								}
      });
    }
  ); //endpost
  $('.top_cart').parent().show();
  setTimeout( 'hide_prepopup()', 2000 );
  //hide_prepopup();
}

function set_sort( type,ev ){
    $('.sort_block a').attr( 'class','' );
    $(ev.target).addClass('selected');
    //var path1 = window.location.href;
    //path1 = path1.substring( path1.lastIndexOf('gallery/')+'gallery/'.length );
    $.post( '/gallery/setsort/'+type+"/1","",function(data){
      $('.gallery_page .items').empty().html(data);

    $("a.fancybox").attr('rel', 'gallery').fancybox({
				'titlePosition'	:	'over',
    'padding'	    	: 0,
    'showCloseButton'	: false,
    'overlayColor'  : '#fff',
    'transitionIn'	:	'elastic',
				'transitionOut'	:	'elastic',
    'titleFormat'   : function(title, currentArray, currentIndex, currentOpts) {
                    if ( title.split('||')[3]!=0 )
                      var buy = '<div class="cart_link" rel="'+title.split('||')[2]+'" title="Цена: '+title.split('||')[3]+' $"><a href="javascript:void(0);"><b>купить</b></a> за '+title.split('||')[3]+' $';
                    else var buy ='';
                    return '<span id="fancybox-title-over"><span class="title_span">' + title.split('||')[0] +
                    '&nbsp;<br /> <a class="fancybox-title" id="'+title.split('||')[2]+'" href="/autors/name/'+title.split('||')[1]+'">Перейти на страницу автора</a></span>&nbsp;'+
                    '<div style="display:inline;"> '+buy+'</div><a style="float:right;color:#fff;margin-left:10px;" href="javascript:;" onclick="$.fancybox.close();">закрыть</a><small style="float:right;">'+(currentIndex + 1) + ' из ' + currentArray.length + '</small></div></span>'; },
	   'speedIn'	  	:	600,
				'speedOut'		:	200,
				'onComplete'	:	function() {
          $.post( '/gallery/rate/'+$("a.fancybox-title").attr("id"),"",function(data){});
					$("#fancybox-wrap").mouseover(function() {
						$("#fancybox-title").show();
					}).mouseout( function() {
						$("#fancybox-title").hide();
					});
				 }
        });
    });

    $('.price_label').hide();
				$('.image_gallery').live( {
      mouseover: function() {
								$('.price_label').hide();
        $(this).find('.price_label').show();
      },
      mouseout: function() {
        $('.price_label').hide();
      }
				} );

  }

function hide_prepopup(){
   $("#prepopup").hide();
   $("#prepopup-bg").hide();
}

function show_prepopup( text ){
    var pos = gss();
    documentWidth=pos.ww/2+pos.wsl-($("#prepopup").width()/2);
  	 documentHeight=pos.wh/2+pos.wst-($("#prepopup").height()/2);
    $("#prepopup").show();
    $("#prepopup").alignCenter();
    //$("#errpopup").css( 'left',($(window).width()  - $('#errpopup').outerWidth())/2 );
    //$("#errpopup").css( 'top', (documentHeight + $('#errpopup').outerHeight())/2 );
    $("#prepopup").css( 'top', 0);
    $("#prepopup").css( 'margin-top', pos.wh/2-($("#prepopup").height()/2));
    $("#prepopup").css( 'position', 'fixed');
    $('.prepopup-in').html(text);
    $("#prepopup-bg").show();
}

function gss() {
  var w = document.documentElement; var d = document.body;
  if (w.scrollHeight < d.scrollHeight) { var h = d.scrollHeight } else { var h = w.scrollHeight } if (h<w.clientHeight) { h = w.clientHeight }
  if (w.scrollWidth < d.scrollWidth) { var wd = d.scrollWidth } else { var wd = w.scrollWidth } if (wd<w.clientWidth) { wd = w.clientWidth }
  return { ww:w.clientWidth, wh:w.clientHeight, wsl:w.scrollLeft, wst:w.scrollTop, dw:wd, dh:h }
}

$(document).ready(function(){

  //align element in the middle of the screen
  $.fn.alignCenter = function() {
      //get margin left
   var marginLeft = - $(this).width()/2 + 'px';
   //get margin top
   var marginTop =  $(this).height()/2 + 'px';
   //return updated element
   return $(this).css({'margin-left':marginLeft, 'margin-top':marginTop});

  };
});
