
(function($) {
  $(function() {
    $(document).ready(function(){
		$.fn.dataTableExt.oSort['numeric-comma-asc']  = function(a,b) {
			var x = (a == "-") ? 0 : a.split(/ /).join('');
			var y = (b == "-") ? 0 : b.split(/ /).join('');
			x = parseFloat( x );
			y = parseFloat( y );
			return ((x < y) ? -1 : ((x > y) ?  1 : 0));
		};
		 
		$.fn.dataTableExt.oSort['numeric-comma-desc'] = function(a,b) {
			var x = (a == "-") ? 0 : a.split(/ /).join('');
			var y = (b == "-") ? 0 : b.split(/ /).join('');
			x = parseFloat( x );
			y = parseFloat( y );
			return ((x < y) ?  1 : ((x > y) ? -1 : 0));
		};	
		$('table.tablesorter').each(function (i) {
			var cols=new Array();
			$('th', this).each(function (i) {cols[i] = null});
			cols[cols.length-1] = { "sType": "numeric-comma" };
			
			oTable = $(this).dataTable({
				"bPaginate": false,
				"bLengthChange": false,
				"bFilter": false,
				"bSort": true,
				"bInfo": false,
				"bAutoWidth": false,		
				"fnDrawCallback": function ( oSettings ) {
					if ( oSettings.aiDisplay.length == 0 )
					{
						return;
					}
					
					var nTrs = $('tbody tr', this);
					var iColspan = nTrs[0].getElementsByTagName('td').length;
					var sLastGroup = "";
					for ( var i=0 ; i<nTrs.length ; i++ )
					{
						var iDisplayIndex = oSettings._iDisplayStart + i;
						var sGroup = oSettings.aoData[ oSettings.aiDisplay[iDisplayIndex] ]._aData[0];
						if ( sGroup != sLastGroup )
						{
							var nGroup = document.createElement( 'tr' );
							var nCell = document.createElement( 'td' );
							nCell.colSpan = iColspan;
							nCell.className = "group";
							nCell.innerHTML = sGroup;
							nGroup.appendChild( nCell );
							nTrs[i].parentNode.insertBefore( nGroup, nTrs[i] );
							sLastGroup = sGroup;
						}
					}
				},
				"aoColumnDefs": [
					{ "bVisible": false, "aTargets": [ 0 ] }
				],
				"aaSortingFixed": [[ 0, 'asc' ]],
				"aaSorting": [[ 1, 'asc' ]],
				"sDom": 'lfr<"giveHeight"t>ip',
				"aoColumns": cols
			});	
		});
	  /*$('table.tablesorter').tablesorter()
		.bind("sortEnd", function(){
			//ungroup first
			$(this).tableUnGroup();
			$(this).tableGroup({groupColumn: 1, groupClass: 'cat-groups', useNumChars: 0});
 	  });*/
      $('.br').each(
        function(){
          if ($(this).children().length > 1)
            $($(this).find('img')[1]).hide();
		  $($(this).find('img')[0]).addClass('on'+$(this).attr('_id'));	
		  $($(this).find('img')[1]).addClass('off'+$(this).attr('_id'));	
        }).hover(
        function(){
            $('.off'+$(this).attr('_id')).fadeIn(100);
            $('.on'+$(this).attr('_id')).fadeOut(100);
        },
        function(){
            $('.on'+$(this).attr('_id')).fadeIn(100);
            $('.off'+$(this).attr('_id')).fadeOut(100);
        });

      $(".captcha").each(function() {
        $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
      }).click(function(){
        $(this).attr('src','/si.php?n='+$(this).attr('id')+'&rid=' + Math.random());
      });

      $('#sorder, #scat').each(function(){
        $('body').append($(this).clone().attr('id', $(this).attr('id')+'t').hide());
      }).change(function(){
        var t = $(this).attr('id') == 'scat' ? '#sorder' : '#scat';
        var r = $(t).val();
        if ($(t).length) {
          if ($(this).val() > 0) {           
            $(t+' option[value!=""]').remove();
            $.each($(this).find('option:selected').attr('_refer').split(','),
              function(){
                $(t).append($(t+'t option[value='+this+']').clone());
              });
            $(t).val(r);
          }
          else {
            $(t+' option').remove();
            $(t).append($(t+'t option').clone());
            $(this).find('option').remove();
            $(this).append($('#' + $(this).attr('id')+'t option').clone());
          }
        }
      });
      $('.smt').click(function(){
        $(this).parent().submit();
        return false;
      });
      $('#filter').click(function(){
        var t = $(this).parents('form:first');
        t.find('input[value != ""][type != submit], select[value != ""]').each(function(){
          t.attr('action', t.attr('action') + $(this).attr('name')+$(this).val()+'/');
        });
        t.submit();
      });
      $('#logout').click(function(){
        $(this).parent().submit();
        return false;
      });
      $('#order_status input[type=submit]').click(function(){
         var temp=$('#order_status');
         $.post(temp.attr('action'), temp.serializeArray(), function (data) {$('#dstatus').text(' Сохранено ');});
         return false;
      });

      $('#ppage').change(function(){window.location = $(this).val();});
      if ($('#upload').length)    {
        var btnUpload=$('#upload');
        var status=$('#files');
        var extention = '';
        new AjaxUpload(btnUpload, {
          action: '/feedback/engineer/',
          name: 'uploadfile',
          onSubmit: function(file, ext){
            var re = new RegExp($('#aes').val());
            if (! (ext && re.test(ext))){
              // extension is not allowed
              status.text('Данный формат не поддерживается.').addClass('error');
              return false;
            }
            extention = ext;
            status.addClass('success').text('Загрузка...');
          },
          onComplete: function(file, response){
            //Add uploaded file to list
            if($.trim(response)==="success"){
              $('#request').val(file);
              if ((extention && /^(jpg|jpeg|gif|png|bmp)$/.test(extention))){
                file = '<img src="/images/fd/temp.jpg?'+Math.random()+'" alt="" id="preview"/><br/>'+file;
              }
              status.html(file).addClass('success').removeClass('error');
            } else{
              status.text(file+'- ошибка загрузки: '+response).addClass('error').removeClass('success');
            }
          }
        });
      }
	 if ($('#pdate').length) { 	
		 $('#pdate').datepicker({
			inline: true,
			defaultDate: $.datepicker.parseDate('yy-mm-dd', $('#pdate2').val()),
			onSelect: function(dateText, inst) {$('#pdate2').val(dateText);}
		  });
	  }
	  if ($('#ldate').length) { 
		  $('#ldate').datepicker({
			 inline: true,
			 defaultDate: $.datepicker.parseDate('yy-mm-dd', $('#ldate2').val()),
			 onSelect: function(dateText, inst) {$('#pdate').datepicker('setDate', $('#ldate').datepicker('getDate'));$('#pdate2, #ldate2').val(dateText);}
		  });
	  }
    });
  });
})(jQuery);



