function module_domready()
{	wallpapers_domready();}

function clickNext()
{
	if (jQuery('#nextlink'))
	{	    redirect(jQuery('#nextlink').attr('href'));
    }}

function noveton()
  {
  var myURI = new URI(document.location);
  var host = myURI.get('host');
  if (host.match(/veton\.ru/))
    {
    myURI.set('host',host.replace(/veton\.ru/,'vetton.ru'));
    var replaced = myURI.toString();
    redirect(replaced);
    }
  }

noveton();

var jcropobj;
var wallpaperCoordinates;
var cropSize;
function cropWallpaper(width,height)
{
	var aspectRatio = width/height;
	var screenRatio = screen.width/screen.height;

	if (!$('originalResolution')) return;

	cropSize = width+'x'+height;

	var originalResolution = $('originalResolution').innerHTML;
    var originalWidth = originalResolution.replace(/x.+/i , '');
    var originalHeight = originalResolution.replace(/.+x/i , '');
    var originalRatio = originalWidth/originalHeight;

    if (!jcropobj)
    {
	    wallpaperCoordinates = $$('#wallpaper')[0].getCoordinates();
    }

	var smallerRate = originalWidth/wallpaperCoordinates.width; // Во сколько раз картинка показываемая пользователю, меньше чем оригинал

	var selRateW = width/wallpaperCoordinates.width; // Во сколько выделенная область меньше, чем показываемая картинка пользователю
	var selRateH = height/wallpaperCoordinates.height; // Во сколько выделенная область меньше, чем показываемая картинка пользователю

 	if (aspectRatio > originalRatio) {  // Режем по ширине
 		var leftMargin = 0; 		var topMargin = (wallpaperCoordinates.height-height/selRateW)/2;
 		var selectionWidth = wallpaperCoordinates.width;
 		var selectionHeight = height/selRateW+topMargin; 	} else { 	    var topMargin = 0;
 		var leftMargin = (wallpaperCoordinates.width-width/selRateH)/2;
 		var selectionWidth = width/selRateH+leftMargin;
 		var selectionHeight = wallpaperCoordinates.height;
 	}

	//alert(leftMargin+' '+topMargin+' '+selectionWidth+' '+selectionHeight);

	(function($) {
    if (jcropobj){

    	jcropobj.animateTo([ leftMargin, topMargin, selectionWidth, selectionHeight]);
	} else {
        jcropobj = $.Jcrop('#wallpaper',{
    		setSelect: [ leftMargin, topMargin, selectionWidth, selectionHeight],
			allowResize:false,
			allowSelect:false,
			onChange: showCoords,
			onSelect: showCoords
        });
    }

    })(jQuery);

    $('cutbutton').setStyle('display','block');
    $('cutbutton').addEvent('click', function (e) {
    	var href = $('cutlink').innerHTML;
    	redirect(href);
    	e.stop();
    });
}

function getItemId() {	return $$('body')[0].getProperty('id').replace(/item/,'');
}


function showCoords(c)
{
	var originalResolution = $('originalResolution').innerHTML;
    var originalWidth = originalResolution.replace(/x.+/i , '');

	var smallerRate = originalWidth/wallpaperCoordinates.width; // Во сколько раз картинка показываемая пользователю, меньше чем оригинал
    var cutArea = Math.round(c.x*smallerRate)+'|'+Math.round(c.y*smallerRate)+'|'+Math.round(c.x2*smallerRate)+'|'+Math.round(c.y2*smallerRate);

	$('cutlink').innerHTML = '/'+getItemId()+'/'+cropSize+'/'+cutArea+'/';
};

function template_domready() /* Выполняется после загрузки страницы */
{
    $$('.mini span').addEvent('mouseover',function() {
    	var img = this.getChildren();
    	if (img[0]) {
	  	    var background = img[0].getProperty('src').replace(/\/138\//,'/260/');

	  	    var smallSize = img[0].getSize();
	  	    var bigHeight = 260/138*smallSize.y;

	  	    img[0].hide();

	        this.addClass('big');
			this.setStyle('background','url('+background+') no-repeat 50% 0px');
	  	    this.setStyle('height',bigHeight+'px');
	  	    this.setStyle('margin-top','-'+smallSize.y/2+'px');

	  	    img[1].setStyle('margin-top',bigHeight+'px');
  	    }
    });

    $$('.mini span').addEvent('mouseout',function() {

  	    var img = this.getChildren();
  	    if (img[0]) {
	  	    var background = '';

	  	    img[0].show();

			this.removeClass('big');
	       	this.setStyle('background','none');
	  	    this.setStyle('height','auto');
	  	    this.setStyle('margin-top','auto');
  	    }
    });

    $$('.mini span small b strong[title]').addEvent('click',function(e) { // Делаем ссылки на страницы пользователей
    	redirect(this.getProperty('title'));
    	e.stop();    });

    new Autocompleter.Request.HTML($$('form#search input')[0], '/ajax/search_autocomplete.php', {
		'postData': {
			'extended': '1' // send additional POST data, check the PHP code
		},
		'filterSubset': true,
		'injectChoice': function(choice) {
			var text = choice.getFirst();
			var value = text.innerHTML;
			choice.inputValue = value;
			text.set('html', this.markQueryValue(value));
			this.addChoiceEvents(choice);
		}
	});

    if ($$('#wallpaper')[0]) // Если находимся на странице загрузки обоев
    {
        var myKeyboardEvents = new Keyboard({
    		defaultEventType: 'keydown',
    		events: {
        		'ctrl+right': clickNext,
    		}
  		});
        if (screen.width) // Если определили разрешение моника
        {
            var screenRatio = screen.width/screen.height;

            $('userScreenResolutionDiv').setStyle('display','block');
        	$('userScreenResolution').innerHTML = screen.width+'x'+screen.height;

            var originalResolutionDiv = $$('.thisWallpaperResolution')[0];
        	if (originalResolutionDiv) {

	            var originalResolution = originalResolutionDiv.innerHTML;
	            var originalWidth = originalResolution.replace(/x.+/i , '');
	            var originalHeight = originalResolution.replace(/.+x/i , '');

	            if (screenRatio == originalWidth/originalHeight) {
	            	originalResolutionDiv.addClass('sameRatio');
	            	$('userScreenResolutionDiv').addClass('sameRatio');

	            	$('userScreenResolution').store('tip:title', 'Пропроции вашего экрана и этой картинки совпадают, она идеально подходит для вашего экрана');

	            } else {
					if ($('userScreenResolutionDiv'))
					{
                        if ($$('html')[0].hasClass('logged')){ // Если залогинен

							if (!$('originalSizeOnCroppedPage')) { // Если находимся на странице оригинальной картики

	        					$('userScreenResolution').addEvent('click',function (e) {
	        						cropWallpaper(screen.width,screen.height);
	        					});

	        				} else {
	        					$('userScreenResolution').setProperty('href','/'+getItemId()+'/'+screen.width+'x'+screen.height+'/');

	        				}

                        } else {
                        	$('userScreenResolution').addEvent('click',function (e) {
	        					users_loginform_show('Для изменения размеров обоев необходимо войти на сайт',findhref());
	        					e.stop();
	        				});

                        }
	        		}

	            }
	        }        }


    $$('#wallpaper')[0].addEvent('click', function (e) {
  		$('wallpaper').toggleClass('ontop');
    });

    $$('#wallpaper')[0].addEvent('mouseenter', function (e) {    	$('fader').setStyle('opacity',0);
  		$('wallpaper').setStyle('z-index',199);
  		$('wallpaper').setStyle('position','relative');
  		$('fader').addClass('white');
  		$('fader').setStyle('display','block');
  		$('fader').setStyle('visibility','visible');
  		$('fader').set('tween', {duration: 500}); $('fader').tween( 'opacity', 0.5 );
  		nextLinkPosition();
    });

    $$('#wallpaper')[0].addEvent('mouseleave', function (e) {
  			$('fader').setStyle('display','none');
  			$('fader').setStyle('visibility','visible');
  			$('wallpaper').setStyle('z-index',99);
  			$('fader').removeClass('white');
  			nextLinkUnHover();
    });

    $('wallpaper').addEvent('load', function (e) {
        set_nextlink_height();
    });

    nextLinkPosition();

	var wallpaperCoordinates = $$('#wallpaper')[0].getCoordinates();

    if ($('nextlink')) {
	    $('nextlink').setStyle('height',wallpaperCoordinates.height+'px');
	    $('wallpaperWrapper').setStyle('min-height',wallpaperCoordinates.height+'px');

	    $('nextlink').setStyle('z-index',209);

	    window.addEvent('resize', function(){
	  		nextLinkPosition();
		});

		$('nextlink').addEvent('mousemove', function (e) {
	    	nextLinkPosition();
	    	});

	    $('nextlink').addEvent('mouseenter', function (e) {
	    	nextLinkHover();
	    	});

	    $('nextlink').addEvent('mouseover', function (e) {
	    	nextLinkHover();
	    	});

	    $('nextlink').addEvent('mouseleave', function (e) {
	    	nextLinkUnHover();
	    	});

	    $('nextlink').addEvent('mouseout', function (e) {
	    	nextLinkUnHover();
	    	});
	    }
    }


  $$('.mini a:visited img').each(function (elem) {
  	elem.addEvent('mouseenter', function (e) { elem.set('tween', {duration: 200}); elem.tween( 'opacity', 1 ); });
    elem.addEvent('mouseleave', function (e) { elem.set('tween', {duration: 200}); elem.tween( 'opacity', 0.5 ); });
  });  $$('.mini_owner img').multiFade();
  //$$('.mini img').multiFade();

  $$('.mini_owner select').each(function(elem) { // Выбор категории обоины в личном кабинете  	elem.addEvent('change',function (e) {  		var id = elem.name.replace(/[^0-9]+?/g,'');

  		if ($('subdir'+id))
          {          $('subdir'+id).empty();          }
  		elem.addClass('ajaxload');
  		var myRequest = new Request({url: '/modules/wallpapers/ajax/edit.php?mode=dir', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {
      		elem.removeClass('ajaxload');
      		lighting('done',elem);
  		}, onFailure: function(err) {  			 lighting('error',elem);
  		}

  		}).send('id='+id+'&value='+elem.value);
  	});
  });

  var input_namedata = new Array();
  $$('.mini_owner input.name').each(function(elem) { // Ввод подкатегории  	 var itemid = elem.getAttribute('itemid'); // Id картинки
  	 elem.addEvents({
       mouseleave: function(){ // Увели курсор с поля - сохраняем
          if (input_namedata[itemid]) // Только в случае если в это поле что-то писали
            {
            savename(elem);
            input_namedata[itemid] = 0;
            }
       },
       blur: function(){
          if (input_namedata[itemid])
            {            savename(elem);
            input_namedata[itemid] = 0;            }
       },
       keydown: function(){ // Ставим метку о том что в этот инпут мы писали
          input_namedata[itemid] = 1;
       },
       focus: function(){ // Ставим метку о том что в этот инпут мы писали
          input_namedata[itemid] = 1;
       }
    });

  });

  var input_tagsdata = new Array();
  $$('.mini_owner input.tags').each(function(elem) { // Указывание тегов
    var itemid = elem.getAttribute('itemid'); // Id картинки

  	elem.addEvent('keydown',function (e) {
    	if (!input_tagsdata[itemid])
          {
          var savebtn = new Element('input', {'type': 'submit', 'class':'button', 'value':'Сохранить', 'onClick':'javascript:save_tags(\'wallpapers\',\''+itemid+'\',\'input_tags'+itemid+'\');this.hide();'});
    	  $$('#tags'+itemid+' span').dispose();
    	  $('tags'+itemid).adopt(savebtn);
          input_tagsdata[itemid] = 1;
          }
  	});
  });


  yaCounter49237.hit(findhref(),document.title,null);
  }

function set_nextlink_height() {
    if ($('nextlink'))
	{
	    var wallpaperCoordinates = $$('#wallpaper')[0].getCoordinates();
	    $('nextlink').setStyle('height',wallpaperCoordinates.height+'px');
        $('nextlink').getChild().setStyle('height',wallpaperCoordinates.height+'px');
    }
}

function nextLinkPosition()
{
	if ($('nextlink'))
	{	    var wallpaperCoordinates = $$('#wallpaper')[0].getCoordinates();
        $('nextlink').setStyle('top',wallpaperCoordinates.top+'px');
        $('nextlink').setStyle('left',(wallpaperCoordinates.right-85)+'px');    }
}

function nextLinkUnHover()
{	if ($('nextlink')) $('nextlink').removeClass('hover');}

function nextLinkHover()
{
	if ($('nextlink')) $('nextlink').addClass('hover');
}

function savename(elem)
  {  var id = elem.name.replace(/[^0-9]+?/g,'');

  elem.addClass('ajaxload');
  		      var myRequest = new Request({url: '/modules/wallpapers/ajax/edit.php?mode=name', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {
      		      elem.removeClass('ajaxload');
      		      elem.removeClass('error');
      		      lighting('done',elem);
  		        }, onFailure: function(err) {
  			      lighting('error',elem);
  		        }

  }).send('id='+id+'&value='+elem.value);  }

function insert_subdir_input(id,parent,value) // Вставляет текстовое поле в которое можно ввести новый подраздел
  {
  if ($('subdir'+id))
    {    $('subdir'+id).innerHTML = '<input autocomplete="/modules/wallpapers/ajax/autocomplete_dirs.php?parent='+parent+'" placeholder="Название подкатегории" type="text" id="input_subdir'+id+'" parent="'+parent+'" itemid="'+id+'" value="'+value+'">';

    init_inputs('#subdir'+id);

    var input_newdata = new Array();
    $('input_subdir'+id).addEvent('focus',function(e) { // При фокусе показываем кнопку "сохранить"    	if (!input_newdata[id])
    	  {
    	  var savebtn = new Element('input', {'type': 'submit', 'class':'button','value':'Сохранить', 'onClick':'javascript:save_subdir(\'input_subdir'+id+'\');'});    	  $('subdir'+id).adopt(savebtn);    	  }    	input_newdata[id] = 1;      });
    }  }

function save_subdir(id)
  {
  elem = $(id);
  var parent = parseInt(elem.getAttribute('parent'));
  var itemid = parseInt(elem.getAttribute('itemid'));

  $$('#subdir'+itemid+' input[type=submit]')[0].hide();
  elem.addClass('ajaxload');
  		      var myRequest = new Request({url: '/modules/wallpapers/ajax/dirs.php?mode=new', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {
      		      elem.removeClass('ajaxload');
      		      elem.removeClass('error');
      		      lighting('done',elem);
  		        }, onFailure: function(err) {
  			      lighting('error',elem);
  		        }
    }).send('itemid='+itemid+'&parent='+parent+'&value='+elem.value);

  }

function lighting(mode,elem)
  {
  switch(mode)
    {    case 'done':
    elem.set('tween', {
	  link: 'chain'
    }).tween('border', '1px solid #32a200').pauseFx(1000).tween('border', '1px solid #CED9E6');    break;
    case 'error':
    elem.set('tween', {
	  link: 'chain'
    }).tween('border', '1px solid #ff0000').pauseFx(1000).tween('border', '1px solid #CED9E6');
    break;
    }
  }

function changeLetter(letter,obj)
  {
  // Буквы
  if (!letter)
    {    $$('#hreflist div.letter').setStyle('display','block');    }

  $$('#letterlist a').removeClass('selected'); // Очищаем классы  obj.addClass('selected'); // Добавляем класс

  $$('#hreflist a, #hreflist div.letter').each(function(elem) {  		var name = elem.get('text');    	if (!letter || name[0].toUpperCase() == letter || (letter == '0-9' && is_int(name[0])))
    	  {    	  elem.setStyle('display','block');    	  }
    	else
    	  {    	  elem.setStyle('display','none');    	  }
  	});

  return false;  }

function makecols(id,cols,byDiv)
  {
  var tag = (byDiv)?'div':'a';
  var kolvo = 0;
  $$('#'+id+' a').each(function (element) {
    kolvo++; // Считаем количество элементов
    })

  var width = Math.floor(100/cols);

  for(var i=0;i<cols;i++) // Создаем колонки
    {
    colElement = new Element('div', {'id': 'col'+i,'class':'col','styles':{'width': width+'%','float':'left'}});
    $('temp').adopt(colElement);
    }

  var counter = 1;
  var col =0;
  $$('#'+id+' a, #'+id+' div').each(function (elem) {
    	if (elem.get('tag') == tag)
    	  {
    	  if (counter >= Math.ceil(kolvo/cols))
    	    {    	    col++;
    	    counter=1;    	    }
    	  }
    	else
    	  {    	  counter++;    	  }
    	if (col >= cols) col--; // Чтоб не переполнялась

    	$('col'+col).adopt(elem);
    	//alert(col);
  	});

  clearElement = new Element('div', {'class':'clear'});
  $('temp').adopt(clearElement);

  $('hreflist').innerHTML = $('temp').innerHTML;
  $('temp').empty();  }

function template_users_update_userbar()
  {  ajaxload('/custom/leftcol.php','leftcol',1);  }


function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else {
      return false;
  }
}

function wallpapers_minwidth(value)
  {
  var myRequest = new Request({url: '/custom/ajax/minwidth.php', method: 'post', evalScripts: true, onSuccess: function(responseText, responseXML) {
     ajaxload(findhref());
  }}).send('width='+value);
  }
