function empty( mixed_var ) {   // Determine whether a variable is empty
    //
    // +   original by: Philippe Baumann
 
    return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  || mixed_var === false );
}

$(document).ready(function() {  
		var size_prop = 1;
		var size_koef = 1;
		var jcrop_coord = null;
		var jcrop_bounds = null;
    var vid_prod = null; 

    var prod2id = {'art_paneli':3,'murali':4,'fotooboi':5,'freski':1}; 
		
 		function pixel_to_metr(val, koef)
		{           
        koef = koef || size_koef; 
        return Math.round((val/koef)*100)/100;		
		};
		
		function metr_to_pixel(val, koef)
		{           
        koef = koef || size_koef; 
        return Math.round(val*koef);		
		};
		
		function get_w(h)
		{           
        return Math.round((h*size_prop)*100)/100;		
		};
		
		function get_h(w)
		{           
        return Math.round((w/size_prop)*100)/100;		
		};

    function open_img_interface_oncomplete(){

          $("a.tooltip_open").tooltip({
            showURL: false,
          	bodyHandler: function() {
          		var tmp = $(this).attr('rel');
              return $(tmp).html();
  	        }
          });
          
          var jcrop_api = null;
                        
          var kat_size_x = $("#kat_size_x").html();
          var kat_size_y = $("#kat_size_y").html();
          
          var kat_maxsize_x = $("#kat_maxsize_x").html();
          var kat_maxsize_y = $("#kat_maxsize_y").html();
          
          var kat_minsize_x = $("#kat_minsize_x").html();
          var kat_minsize_y = $("#kat_minsize_y").html();
                    
          if ( (kat_size_x === null) ||
               (kat_size_y === null) ||
               (kat_maxsize_x === null) ||
               (kat_maxsize_y === null) ||
               (kat_minsize_x === null) ||
               (kat_minsize_y === null) ){
            //alert("Error: no parametr!");
            return;     
          }
          
          var item_x = $("#item_x").html();
          var item_y = $("#item_y").html();
          var item_ox = $("#item_ox").html();
          var item_oy = $("#item_oy").html();
          var crop_init_flag = true; 
          
          if ( (item_x == '') ||
               (item_y == '') ||
               (item_ox == '') ||
               (item_oy == '') ){
            item_x = 0;
            item_y = 0;
            item_ox = 0;
            item_oy = 0; 
            crop_init_flag = false; 
            //alert("crop_init: 0");  
          } else {           
            item_x = parseFloat(item_x.replace(/,/g, "."));
            item_y = parseFloat(item_y.replace(/,/g, ".")); 
            item_ox = parseFloat(item_ox.replace(/,/g, ".")); 
            item_oy = parseFloat(item_oy.replace(/,/g, "."));            
            //alert('crop_init: ' + item_x + ' / ' + item_y + ' / ' + item_ox + ' / ' + item_oy + ' / ');             
          } 
          
          var item_w = $("#item_w").html();
          var item_h = $("#item_h").html(); 
          var size_init_flag = true; 

          if ( (item_w == '') ||
               (item_h == '') ){
            item_w = 0;
            item_h = 0;
            size_init_flag = false; 
            //alert("size_init: 0");  
          } else {           
            item_w = parseFloat(item_w.replace(/,/g, "."));
            item_h = parseFloat(item_h.replace(/,/g, "."));          
            //alert('size_init: ' + item_w + ' / ' + item_h + ' / ');             
          }  
          
          var item_in_gal = $("#item_in_gal").html();
          if (item_in_gal == '1'){
            item_in_gal = true;
          } else {
            item_in_gal = false;
          } 

          // -----------------------
          var vid_prod = $("#vid_prod_val").html();          
          if ( vid_prod == '' ){
            vid_prod = 0; 
          } else {           
            vid_prod = parseFloat(vid_prod.replace(/,/g, "."));            
          } 
          //alert(vid_prod);          
          if (vid_prod != 0)
             $("#vid_prod").val(vid_prod); 
          // -----------------------
          var mat_type_1 = $("#mat_type_val_1").html();          
          if ( mat_type_1 == '' ){
            mat_type_1 = 0; 
          } else {           
            mat_type_1 = parseFloat(mat_type_1.replace(/,/g, "."));            
          }         
          if (mat_type_1 != 0)
             $("#mat_type_1").val(mat_type_1); 
             
          var mat_type_3 = $("#mat_type_val_3").html();          
          if ( mat_type_3 == '' ){
            mat_type_3 = 0; 
          } else {           
            mat_type_3 = parseFloat(mat_type_3.replace(/,/g, "."));            
          }         
          if (mat_type_3 != 0)
             $("#mat_type_3").val(mat_type_3); 
             
          var mat_type_4 = $("#mat_type_val_4").html();          
          if ( mat_type_4 == '' ){
            mat_type_4 = 0; 
          } else {           
            mat_type_4 = parseFloat(mat_type_4.replace(/,/g, "."));            
          }         
          if (mat_type_4 != 0)
             $("#mat_type_4").val(mat_type_4); 
             
          var mat_type_5 = $("#mat_type_val_5").html();          
          if ( mat_type_5 == '' ){
            mat_type_5 = 0; 
          } else {           
            mat_type_5 = parseFloat(mat_type_5.replace(/,/g, "."));            
          }         
          if (mat_type_5 != 0)
             $("#mat_type_5").val(mat_type_5); 
          // -----------------------              

          //alert(kat_size_x + '/' + kat_size_y ); 
                   
          kat_size_x = parseFloat(kat_size_x.replace(/,/g, "."));
          kat_size_y = parseFloat(kat_size_y.replace(/,/g, "."));                                        
          //alert("kat_size_x: " + kat_size_x + " , kat_size_y: " + kat_size_y); 

          kat_maxsize_x = parseFloat(kat_maxsize_x.replace(/,/g, "."));
          kat_maxsize_y = parseFloat(kat_maxsize_y.replace(/,/g, "."));                                        
          //alert("kat_maxsize_x: " + kat_maxsize_x + " , kat_maxsize_y: " + kat_maxsize_y);           

          kat_minsize_x = parseFloat(kat_minsize_x.replace(/,/g, "."));
          kat_minsize_y = parseFloat(kat_minsize_y.replace(/,/g, "."));                                        
          //alert("kat_minsize_x: " + kat_minsize_x + " , kat_minsize_y: " + kat_minsize_y);

          if ( (item_x == kat_size_x)&&(item_y == kat_size_y)&&(item_ox == 0)&&(item_oy == 0) ){
            crop_init_flag = false;  
          }
                    
          if ( (item_w == kat_size_x)&&(item_h == kat_size_y) ){
            size_init_flag = false; 
          } 
          
          size_prop = kat_size_x / kat_size_y;
          
          var img_width = $("#cropbox").width();
          var img_height = $("#cropbox").height();
          
          if (size_init_flag){
            size_koef = img_width / item_w ;
          } else {
            size_koef = img_width / kat_size_x ;
          }                        
                    
          if( (kat_maxsize_x == 0) && (kat_maxsize_y == 0) ){
      		    kat_maxsize_x = kat_size_x*2;
              kat_maxsize_y = kat_size_y*2;
              //alert("kat_maxsize_x: " + kat_maxsize_x + " , kat_maxsize_y: " + kat_maxsize_y);			         
          }
          
          if( (kat_minsize_x == 0) && (kat_minsize_y == 0) ){
      				if (size_prop > 1){
                  kat_minsize_x = 0.5;
                  kat_minsize_y = get_h(kat_minsize_x);                
              } else {
                  kat_minsize_y = 0.5;
                  kat_minsize_x = get_w(kat_minsize_y);                                  
              }
              //alert("kat_minsize_x: " + kat_minsize_x + " , kat_minsize_y: " + kat_minsize_y);         
          }           
          
          var new_w = null;
          var new_h = null;
          var new_size_koef = size_koef;
          
          /* -- Укажите свой размер -------------------- */
          
          var api_new_w = {};
          var api_new_h = {};
          var api_crop_w = {};
          var api_crop_h = {};
          
          var jcrop_showCoords = true;
          
          if (size_init_flag){
              $("#new_w").val(item_w);
              $("#new_h").val(item_h);          
          } else {
              $("#new_w").val(kat_size_x);
              $("#new_h").val(kat_size_y);
          }
          $("#crop_w").val(0);
          $("#crop_h").val(0);              
          
          api_new_w = $("#new_w").live_input({
            min: kat_minsize_x,
            max: kat_maxsize_x,
            messageBox: '#set_razmer_error',
            onChange: function(val){
              new_w = val;
              new_h = get_h(val);
              new_size_koef = img_width / new_w ;  
              api_new_h.setVal_stealth( new_h );              
              if ((jcrop_api !== null) && (jcrop_coord !== null)){
                  //api_crop_w.set_max( pixel_to_metr(jcrop_bounds[0] - jcrop_coord.x, new_size_koef) ); 
                  //api_crop_h.set_max( pixel_to_metr(jcrop_bounds[1] - jcrop_coord.y, new_size_koef) );
                  var mw = (new_w === null) ? kat_size_x : new_w; 
                  var mh = (new_h === null) ? kat_size_y : new_h;        
                  api_crop_w.set_max( mw );              
                  api_crop_h.set_max( mh );  
                                   
                  api_crop_w.setVal_stealth( pixel_to_metr(jcrop_coord.w, new_size_koef) );                    
                  api_crop_h.setVal_stealth( pixel_to_metr(jcrop_coord.h, new_size_koef) );
                  jcrop_api.setOptions({ minSize: [ metr_to_pixel(kat_minsize_x, new_size_koef), metr_to_pixel(kat_minsize_y, new_size_koef) ] });  
              } 
            },
            onShowMessage: function(){
              fos_open_func();
            }
          }).live_input();
          
          api_new_h = $("#new_h").live_input({
            min: kat_minsize_y,
            max: kat_maxsize_y,
            messageBox: '#set_razmer_error',
            onChange: function(val){  
              new_h = val;
              new_w = get_w(val);
              var tmp = api_new_w.setVal_stealth(new_w);
              if (new_w != tmp){                 
                new_h = get_h(tmp);
                api_new_h.setVal_stealth( new_h );
              }
              new_size_koef = img_width / new_w ;
              if ((jcrop_api !== null) && (jcrop_coord !== null)){
                  api_crop_w.set_max( pixel_to_metr(jcrop_bounds[0] - jcrop_coord.x, new_size_koef) ); 
                  api_crop_w.setVal_stealth( pixel_to_metr(jcrop_coord.w, new_size_koef) );
                  api_crop_h.set_max( pixel_to_metr(jcrop_bounds[1] - jcrop_coord.y, new_size_koef) ); 
                  api_crop_h.setVal_stealth( pixel_to_metr(jcrop_coord.h, new_size_koef) );
                  jcrop_api.setOptions({ minSize: [ metr_to_pixel(kat_minsize_x, new_size_koef), metr_to_pixel(kat_minsize_y, new_size_koef) ] });
              } 
            },
            onShowMessage: function(){
              fos_open_func();
            }
          }).live_input();
          
          /* -- Обрезка изображения -------------------- */
          
          api_crop_w = $("#crop_w").live_input({
            messageBox: '#set_crop_error',
            onChange: function(val){  
              if (jcrop_coord !== null){
                jcrop_showCoords = false;
                var val_w = jcrop_coord.x + metr_to_pixel(val,new_size_koef);
                var val_x = jcrop_coord.x;
                if (val_w > jcrop_bounds[0]){
                    var tmp = val_w - jcrop_bounds[0];
                    val_x = jcrop_coord.x - tmp;
                    val_x = (val_x < 0) ? 0 : val_x;
                    val_w = jcrop_bounds[0];  
                }
                jcrop_coord.x = val_x;
                $("#crop_x").val(pixel_to_metr(val_x, new_size_koef));                
                jcrop_coord.x2 = val_w;
                jcrop_api.animateTo( [ val_x, jcrop_coord.y, val_w, jcrop_coord.y2 ], function(){
                  jcrop_showCoords = true;
                });
              }
            },
            onShowMessage: function(){
              fos_open_func();
            }
          }).live_input();
          
          api_crop_h = $("#crop_h").live_input({
            messageBox: '#set_crop_error',
            onChange: function(val){  
              if (jcrop_coord !== null){
                jcrop_showCoords = false;
                var val_h = jcrop_coord.y + metr_to_pixel(val,new_size_koef);
                var val_y = jcrop_coord.y;
                if (val_h > jcrop_bounds[1]){
                    var tmp = val_h - jcrop_bounds[1];
                    val_y = jcrop_coord.y - tmp;
                    val_y = (val_y < 0) ? 0 : val_y;
                    val_h = jcrop_bounds[1];  
                }
                jcrop_coord.y = val_y;
                $("#crop_y").val(pixel_to_metr(val_y, new_size_koef)); 
                jcrop_coord.y2 = val_h;
                jcrop_api.animateTo( [ jcrop_coord.x, val_y, jcrop_coord.x2,  val_h], function(){
                  jcrop_showCoords = true;
                });
              }
            },
            onShowMessage: function(){
              fos_open_func();
            }
          }).live_input(); 
          
          var on_show_kratnTest = 0;
          
      		function showCoords(c)
      		{           
              if (jcrop_showCoords){
                  jcrop_coord = c;
                  //api_crop_w.set_max( pixel_to_metr(jcrop_bounds[0] - c.x, new_size_koef) );              
                  //api_crop_h.set_max( pixel_to_metr(jcrop_bounds[1] - c.y, new_size_koef) );   
                  //api_crop_w.set_max( pixel_to_metr(jcrop_bounds[0], new_size_koef) );              
                  //api_crop_h.set_max( pixel_to_metr(jcrop_bounds[1], new_size_koef) );                 
                  
                  var mw = (new_w === null) ? kat_size_x : new_w; 
                  var mh = (new_h === null) ? kat_size_y : new_h;        
                  api_crop_w.set_max( mw );              
                  api_crop_h.set_max( mh ); 
                  
                  var new_ww = pixel_to_metr(c.w, new_size_koef);
                  var new_w_real = api_crop_w.setVal_stealth( new_ww );  
                 	api_crop_h.setVal_stealth( pixel_to_metr(c.h, new_size_koef) );
                  
                  // для кратности 
                  clearTimeout(on_show_kratnTest);
                  on_show_kratnTest = setTimeout(function(){
                      if (new_ww != new_w_real){
                        jcrop_showCoords = false;
                        jcrop_api.animateTo( [ jcrop_coord.x, jcrop_coord.y, jcrop_coord.x + metr_to_pixel(new_w_real, new_size_koef), jcrop_coord.y2 ], function(){
                          jcrop_showCoords = true;
                        });
                      }                   
                  }, 1000);
                   
                  $("#crop_x").val(pixel_to_metr(c.x, new_size_koef));
                  $("#crop_y").val(pixel_to_metr(c.y, new_size_koef)); 

              }           		
      		}; 
      		
      		/* ------------------------- */
      		
      		var crop_init = function()
          {
              if (vid_prod != prod2id['art_paneli'])
              {
                  $("div.ii_scrollable_cont").hide();
                  $("#iim_send").hide();
                  $("#iim_open").removeClass("current");
                  
                  jcrop_api = $.Jcrop('#cropbox', {
          					onChange: showCoords,
          					onSelect: showCoords,
          					minSize: [ metr_to_pixel(kat_minsize_x, new_size_koef), metr_to_pixel(kat_minsize_y, new_size_koef) ]
          				});              

                  jcrop_bounds = jcrop_api.getBounds();
                  if (crop_init_flag) {                    
                     jcrop_api.animateTo( [ metr_to_pixel(item_ox, new_size_koef), metr_to_pixel(item_oy, new_size_koef), metr_to_pixel(item_ox+item_x, new_size_koef), metr_to_pixel(item_oy+item_y, new_size_koef) ] );
                     //crop_init_flag = false; 
                  } else {                            					   
                     jcrop_api.animateTo( [ 100, 100, jcrop_bounds[0]-100, jcrop_bounds[1]-100 ] );
                  }
                  api_crop_w.set_min(kat_minsize_x);
                  api_crop_h.set_min(kat_minsize_y);                
              }         
          }
          
      		var crop_destroy = function()
          {
              if (vid_prod != prod2id['art_paneli'])
              {
                  jcrop_api.destroy();                  
                  jcrop_api = null;
                  api_crop_w.set_min(null);
                  api_crop_h.set_min(null);
                  api_crop_w.setVal_stealth(0);
                  api_crop_h.setVal_stealth(0);                  
                  $("#crop_x").val(0);
                  $("#crop_y").val(0);                       
              }         
          }
          
      		var set_razmer_destroy = function()
          {
              if (vid_prod != prod2id['art_paneli'])
              {
                  api_new_w.setVal(kat_size_x);
                  api_new_h.setVal(kat_size_y);
              } 
          }
      		         
          $("#open_set_razmer").click(function() 
          {
              var obj = {};
              if (vid_prod == prod2id['art_paneli']){
                  obj = $("div.set_razmer_error");
              } else{
                  obj = $("div.set_razmer");
              } 
              if( !obj.is(':visible') ) 
              {                  
                  obj.show();
              } else {
                  obj.hide();
                  set_razmer_destroy();
              }
              $.fancybox.resize();
              return false; 
          });
          
          if (size_init_flag) {
            $("#open_set_razmer").click();
          }
          
          $("#open_set_crop").click(function() 
          {
              var obj = {};
              if (vid_prod == prod2id['art_paneli']){
                  obj = $("div.set_crop_b_error");
              } else{
                  obj = $("div.set_crop");
              } 
              if( !obj.is(':visible') ) 
              {                  
                  obj.show();                  
                  crop_init();
              } else {
                  obj.hide();
                  crop_destroy();
              }
              $.fancybox.resize();
              return false; 
          });
          
          if (crop_init_flag) {
            $("#open_set_crop").click();  
          }
      		
          /* -- Select Dид продукции ------------------------------------------- */ 

          $('.mat_type').change(function() {
             var vid_mat = $(this).val();
             var id_prod = $(this).attr('id');
             id_prod = id_prod.substr(9,id_prod.length-9);
//alert('prod_type:'+id_prod+',mat_type:'+vid_mat);
             // Номенклатурный номер 
             $("p.nom_num span").hide();
             $("p.nom_num span.art_"+id_prod+'_'+vid_mat).show();
          });

//          $('#mat_type_fotooboi').change(function() {
//             var vid_mat = $('#mat_type_fotooboi').val();

//             // Номенклатурный номер 
//             $("p.nom_num span").hide();
//             $("p.nom_num span.fotooboi_"+vid_mat).show();
//          });

//          $('#mat_type_freski').change(function() {
//             var vid_mat = $('#mat_type_freski').val();

             // Номенклатурный номер 
//             $("p.nom_num span").hide();
//             $("p.nom_num span.freski_" +vid_mat).show();
//          });
          
          $("#vid_prod").change(function () {
             vid_prod = $(this).val();
//             var vid_mat = vid_prod=='fotooboi' ? $('#mat_type_fotooboi').val() : (vid_prod=='freski' ? $('#mat_type_freski').val() : false);
             var vid_mat = $('#mat_type_'+vid_prod).val();

             // Номенклатурный номер 
             $("p.nom_num span").hide();
             $("p.nom_num span.art_" + vid_prod + (vid_mat ? ('_'+vid_mat) : '')).show();
//alert("p.nom_num span.art_" + vid_prod + (vid_mat ? ('_'+vid_mat) : ''));

             // мурали                          
             if(vid_prod == prod2id['murali']){
                api_new_w.set_chag("0.25");
                api_new_w.change();                
                api_crop_w.set_chag("0.25");
                api_crop_w.change();
             }else{
                api_new_w.set_chag(null);
                api_crop_w.set_chag(null);
             }

             // Арт-панели
             if (vid_prod == prod2id['art_paneli']){
                var obj = $("div.set_razmer");
                if( obj.is(':visible') ) 
                { 
                    obj.hide();
                    $("div.set_razmer_error").show();
                }
                
                var obj = $("div.set_crop");
                if( obj.is(':visible') ) 
                { 
                    obj.hide();
                    jcrop_api.destroy();
                    $("div.set_crop_b_error").show();
                }                  
             }else{
                var obj = $("div.set_razmer_error");
                if( obj.is(':visible') ) 
                { 
                    obj.hide();
                    $("div.set_razmer").show();
                } 
                
                var obj = $("div.set_crop_b_error");
                if( obj.is(':visible') ) 
                { 
                    obj.hide();
                    $("div.set_crop").show();
                    crop_init();
                } 
             }
             
             $(".mat_type").hide();
             $('#mat_type_'+vid_prod).show();
             //$("#st_type").hide();
//             if((vid_prod == "murali") || (vid_prod == "art_paneli")){
//                $("#st_type").show();
//             }else{
//                switch(vid_prod){
//                  case 'fotooboi':$("#mat_type_fotooboi").show();break;
//                  case 'freski':$("#mat_type_freski").show();break;
//                }
//             }
             
             //$.fancybox.resize();
          }).change();      		
          
          /* --------------------------------------- */              
                        
          $("div.ii_scrollable").scrollable();

          $("#ii_open_scrollable").click(function () {
              var obj = $("div.ii_scrollable_cont");
              if( !obj.is(':visible') ) 
              {                  
                  obj.show();
                  $.fancybox.resize();
              } else {
                  obj.hide();
                  $.fancybox.resize();  
              }
              return false;
          });
          
          $("#iim_open").click(function () {
              var obj = $("#iim_send");
              if( !obj.is(':visible') ) 
              {                  
                  obj.show();
                  $(this).addClass("current");
                  $.fancybox.resize();
              } else {
                  obj.hide();
                  $(this).removeClass("current");
                  $.fancybox.resize();  
              }
              return false; 
          });     
                    
          // tooltip
          $("a.open_ib_tooltip").hover(function(){
              var obj = $(this).parent().find("div.ib_tooltip");
              if( !obj.is(':visible') ) {
                  obj.show();
                  /*setTimeout(function(){
                    obj.hide();
                  }, 2000); */
              }
              return false;
          },function(){
              $(this).parent().find("div.ib_tooltip").hide();    
          }); 
          
          $("a.open_ib_tooltip").click(function(){ 
            return false; 
          });

          // Подготовка картинки к отсылке в корзину или галерею
          function pre_send_to(){
            var img = '';
            var st= '';
            var cx = '0'; 
            var cy = '0';
            var cw = $("#new_w").val();
            var ch = $("#new_h").val();
                          
            if (jcrop_api !== null){
              cx = $("#crop_x").val(); // metr_to_pixel - переводит метры в пиксели
              cy = $("#crop_y").val();
              cw = $("#crop_w").val();
              ch = $("#crop_h").val();            
            } 

            
            cy = cy.replace(/,/g, ".");
            cw = cw.replace(/,/g, ".");
            ch = ch.replace(/,/g, ".");
            
            $("#crop_x").val(cx); 
            $("#crop_y").val(cy);
            $("#crop_w").val(cw);
            $("#crop_h").val(ch); 

            img = cx + '/' + cy + '/' + cw + '/' + ch + '/' + metr_to_pixel(1, new_size_koef) + '/';
            //alert(img);
            //document.location.href = '/catalog/download/'+$('#img_id').val()+'/'+img;            
            st = '/catalog/download/'+$('#img_id').val()+'/'+$('#vid_prod').val()+'/'+$('#mat_type_'+$('#vid_prod').val()).val()+'/'+img;
            $('#href_to_download').val(st);
            return true;
          }

          // Кнопка "Заказать"
          $('#put_to_basket').click(function(){

            pre_send_to();

            $('#put_to_basket').hide();
            $.post('/basket/add/',$('#img_interface_editor').serialize(),function(res){
              $('#basket_count').load('/basket/count/');
              //alert('Ваш заказ положен в корзину.');
              $("div.img_interface").hide();
              $("#rez_mess").show();
              $.fancybox.resize();
              $('#put_to_basket').show();
            },'html');
            return false;
          });
          
          function iim_send(){
              $('#iim_send_button').hide();
              $.post('/catalog/recomend/',{email:$('#iim_email').val(),mess:$('#iim_mess').val(),img_id:$('#img_id').val()},function(ret){
                  $('#iim_send').html(ret.content);
                  $('#iim_err_msg').html(ret.err);
                  $('#iim_send_button').click(function(){
                      iim_send();
                  });
              },'json');
          }

          // Кнопка отсылки формы "Рекомендовать"
          $('#iim_send_button').click(function(){
              iim_send();
          });
          
          $("a.registr_open").fancybox({
              autoScale: false,
              scrolling: 'visible',
              type: 'ajax',
              padding: 30,
              titleShow: false,
              onComplete: on_registr_open
          }); 

          // Сохранение в личную галерею
          on_save_to_galery = function(){
            pre_send_to();

            var params = $('#img_interface_editor').serialize();
            params += '&target='+$('#add_to_galery_target').val();

            $.post('/home/add/',params,function(res){
              $.fancybox.resize();
              $('#add_to_galery_wait').hide();
              alert(res);
              $.fancybox.close();
            },'html');
          }

          // Кнопка "Скачать"
          $('#img_download, a.btn_ok').click(function()
          {
                if ($(this).attr("class") == 'btn_ok'){
                  if (item_in_gal){

                      on_save_to_galery();

                      return false;
                  }
                }
                
                var img = '';
                var st= '';
                var cx = '0'; 
                var cy = '0';
                var cw = $("#new_w").val();
                var ch = $("#new_h").val();
                
                /*if (vid_prod == prod2id['art_paneli'])
                {
                  cx = 0; 
                  cy = 0;
                  cw = pixel_to_metr(img_width, new_size_koef);
                  ch = pixel_to_metr(img_height, new_size_koef);             
                } else  */                            
                if (jcrop_api !== null){
                  cx = $("#crop_x").val(); // metr_to_pixel - переводит метры в пиксели
                  cy = $("#crop_y").val();
                  cw = $("#crop_w").val();
                  ch = $("#crop_h").val();            
                } 
                
                cx = cx.replace(/,/g, ".");
                cy = cy.replace(/,/g, ".");
                cw = cw.replace(/,/g, ".");
                ch = ch.replace(/,/g, ".");
    
                img = cx + '/' + cy + '/' + cw + '/' + ch + '/' + metr_to_pixel(1, new_size_koef) + '/';
                //alert(img); die();
                //document.location.href = '/catalog/download/'+$('#img_id').val()+'/'+img;            
                st = '/catalog/download/'+$('#img_id').val()+'/'+$('#vid_prod').val()+'/'+$('#mat_type_'+$('#vid_prod').val()).val()+'/'+img;
                
     //alert(st);return false;
                $(this).attr("href", st);

          });  

          /*$("a.open_img_interface").fancybox({
             autoScale: false,
             scrolling: 'visible',
             type: 'ajax',
             onComplete: open_img_interface_oncomplete
      
          }); */
          
          /*$("a.open_inside_img_interface").click(function(){             
            $("div.tmp").html(this);            
            $.fancybox.close();
            //$("#tooltip").hide();
            //$("a.open_inside_img_interface").trigger('click');
            //return false;
          }); */

          $("a.open_inside_img_interface").fancybox({
              autoScale: false,
              scrolling: 'visible',
              type: 'ajax',
              onComplete: open_img_interface_oncomplete      
          });
          
          // кнопка "Перейти в корзину" в сообщении "Ваш заказ помещен в корзину"
          $("#ii_korzina_open").click(function(){
            $("a.korzina_open").click()
            return false;
          });
          
          // Append to user galery 
          $('#add_to_galery_btn').click(function(){
            $('#add_to_galery_btn').css('display','none');
            $('#add_to_galery_frm').css('display','inline');
          });

          // Insert image into user galery
          $('#add_to_galery_submit').click(function(){

            $('#add_to_galery_frm').hide();
            $('#add_to_galery_wait').show();

            on_save_to_galery();

            return false;
          });

          // Change category from user galery 
          $('#move_from_galery_btn').click(function(){
            $('#move_from_galery_btn').css('display','none');
            $('#move_from_galery_frm').css('display','inline');
          });

          // Move image into user galery
          $('#move_from_galery_submit').click(function(){
            pre_send_to();

            var params = $('#img_interface_editor').serialize();
            params += '&target='+$('#move_from_galery_target').val();
            params += '&id_gal='+$('#move_from_galery_current_gal_id').val();

            $('#move_from_galery_frm').hide();
            $('#move_from_galery_wait').show();
            $.post('/home/move/',params,function(res){
              $.fancybox.resize();
              $('#move_from_galery_wait').hide();
              alert('Ваш заказ в галерее.');
              $.fancybox.close();
            },'html');
            return false;
          }); 

      }

    $("a.open_img_interface").fancybox({
      autoScale: false,
      scrolling: 'visible',
      type: 'ajax',
      onComplete: open_img_interface_oncomplete      
    });
    
    $("a.open_img_interface").bind("contextmenu",function(e){
      return false;
    });
    
    $("body").append('<div class="tmp"></div>');
		
});
