function str_replace ( search, replace, subject ) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
 
}

var arrRus = new Array('а', 'ә', 'б', 'в', 'г', 'ғ', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'қ', 'л', 'м',
		                    'н', 'ң', 'о', 'ө','п', 'р', 'с', 'т', 'у', 'ұ', 'ү', 'ф', 'х', 'һ','ц', 'ч', 'ш', 'щ', 'ь',
		                    'ы', 'і', 'ъ', 'э', 'ю', 'я',
		                    'А', 'Ә', 'Б', 'В', 'Г', 'Ғ', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Қ', 'Л', 'М',
		                    'Н', 'Ң', 'О', 'Ө', 'П', 'Р', 'С', 'Т', 'У', 'Ұ', 'Ү', 'Ф', 'Х', 'Һ', 'Ц', 'Ч', 'Ш', 'Щ', 'Ь',
		                    'Ы', 'І', 'Ъ', 'Э', 'Ю', 'Я' );
var arrEng = new Array('a', 'a', 'b', 'v', 'g', 'gh', 'd', 'e', 'jo', 'zh', 'z', 'i', 'y', 'k', 'q', 'l', 'm',
		                    'n', 'ng', 'o', 'o', 'p', 'r', 's', 't', 'u', 'u', 'u', 'f', 'kh', 'h', 'c', 'ch', 'sh', 'sch', '',
		                    'y', 'i', '', 'e', 'ju', 'ja',
		                    'A', 'A', 'B', 'V', 'G', 'G', 'D', 'E', 'JO', 'ZH', 'Z', 'I', 'Y', 'K', 'Q', 'L', 'M',
		                    'N', 'NG', 'O', 'O', 'P', 'R', 'S', 'T', 'U', 'U', 'U', 'F', 'KH', 'H', 'C', 'CH', 'SH', 'SCH', '',
		                    'Y', 'I', '', 'E', 'JU', 'JA');

$().ready(function() {
        $("img").fullsize(); //увеличение изображений
$("a[rel^='prettyPhoto']").prettyPhoto();

	$('#parent-cancel').live('click', function(e) {
		e.preventDefault();
		$('#comment-parent').remove();
		$('#parent_id-element').remove();
		$('#comment').focus();		
		});
	

		//раскрытие настроек пользователя
		$('#c-news-right-menu-udata').hide();
		$('#udata-expand').click(function() {			
			$('#c-news-right-menu-udata').toggle('slow');
			return false;
		});
		
	
		//выделение активного пункта меню
		var zmodule = $('#zmodule').text();
		$('#zmodule').remove();
		if (zmodule){
			var modReg = '/'+zmodule;			
			var pat = new RegExp(modReg, "i");			
			$('.container .c-menu li a').each(function(){
				var modlink = $(this).attr('href'); 
			    if (modlink.search(pat) >= 0)
			    		$(this).parent().addClass('active');
			});
		}
		//навигация по категориям
		var zcaturl = $('#zcaturl').text();
		$('#zcaturl').remove();
		if (zcaturl){
			var catReg = '/'+zcaturl;
			var catpat = new RegExp(catReg, 'i');			
			$('.container .c-container-submenu .c-submenu li a').each(function(){
				var catlink = $(this).attr('href');				
			    if (catlink.search(catpat) >= 0)			    		
			    		$(this).parent().addClass('active');
			});
		}

                var closedialog;
                function overlayclickclose() {
			if (closedialog) {
				$('#logindialog').dialog('close');
          		}
			//set to one because click on dialog box sets to zero
			closedialog = 1;
      		}

		//настройка окна входа	
		$("#logindialog").dialog({
			bgiframe: true,
			autoOpen: false,
                        position: ['right','top'],
			height: 268,
			width: 220,
			zIndex: 3999,
			modal: true,
			resizable: false,
                        open: function(){closedialog = 1;$(document).bind('click', overlayclickclose);},
		focus: function(){closedialog = 0;},
		close: function(){$(document).unbind('click');}

		});		
		
		//открытие окна выхода после щелчка по ссылке		
		$('#login').click(function(ev) {
			ev.preventDefault(); 
			$('#logindialog').dialog('open');
                        $('#username').focus();
                        closedialog = 0;
		});
		
		//закрытие окна выхода		
		$('#cancel').click(function(){
			$('#logindialog').dialog('close');
		});
		
		//коммент		
		$('#submitcomment').click(function(e) {
			e.preventDefault();			
			var form = $('#commentform');
			var commenttext = $('#commentform textarea').val();
			if (commenttext.length > 4) {				
			$.ajax({
                           type: 'post',
			   url: form.attr('action'),			   
			   dataType: 'json',
			   data: form.serialize(),  // this gets the form data
			   beforeSend: function() {
					$('#comment-parent').remove();
					$('#parent_id-element').remove();
					$('#commentform textarea').hide('slow');
					$('#commentform input, textarea').attr('disabled', 'disabled');
                                        $('#submitcomment-element').append('<img id="comment-send" src="/imgs/comment-send.gif" />');
				},
			   success: function(data) {
					var parentid;
					if (data.parent_id > 0) parentid = '<p class="c-comment-reply"><strong>Ответ на комментарий </strong> <a href="#comm'+ data.parent_id + '">№'+ data.parent_id + '</a>:</p>';
					var cCommentHead = $('<div></div>').attr('class', 'c-comment-head')
									.append('<img alt="'+data.uname+'" src="http://'+location.hostname+'/files/images/users/thumb-'+data.pic+'">')
									.append('<a class="c-comment-author" href="http://'+location.hostname+'/user/'+data.uname+'">'+data.uname+'</a>')
									.append('<small class="c-comment-role">user</small>')
									.append('<small class="c-comment-date">только что</small>')
									;
					var cCommentBody = $('<div></div>').attr('class', 'c-comment-body')
									.append(parentid)
									.append(data.comment);
					var cCommentFooter = $('<div></div>').attr('class', 'c-comment-footer')
									.append('<a href="#' + data.c_id + '" name="comm' + data.c_id + '">№ ' + data.c_id + '</a>')
									.append('<a href="#"><strong>Ответить</strong></a>');
					var postcomment = $('<div></div>').attr('id', 'comm' + data.c_id).attr('class', 'c-comment')
										.append(cCommentHead)
										.append(cCommentBody)
										.append(cCommentFooter);
                                        $('#comment-send').remove();
				$(postcomment).appendTo('#allcomments').show('slow');
			   },
			   
			   error: function(xhr, textStatus, errorThrown) {
                           $('#comment-send').remove();
                alert('An error occurred! ' + ( errorThrown ? errorThrown : xhr.status )); 
			   },
			   
			   complete: function() {
					$('#submit-comment').attr('value', 'Добавить комментарий');
					$('#commentform textarea').val('');
					$('#commentform textarea').show('slow');
					$('#commentform input, textarea').removeAttr('disabled', 'disabled');
					
					
				}
			   
			});
			}
			else {
				alert('А давайте писать содержательные комменатрии!');
			}
			  return false;
		});

                $('#comment').keydown(function (e) {

                  if (e.ctrlKey && e.keyCode == 13) {
                    e.preventDefault();
			var form = $('#commentform');
			var commenttext = $('#commentform textarea').val();
			if (commenttext.length > 4) {
			$.ajax({
				type: 'post',
			   url: form.attr('action'),
			   dataType: 'json',
			   data: form.serialize(),  // this gets the form data
			   beforeSend: function() {
					$('#comment-parent').remove();
					$('#parent_id-element').remove();
					$('#commentform textarea').hide('slow');
					$('#commentform input, textarea').attr('disabled', 'disabled');
                                        $('#submitcomment-element').append('<img id="comment-send" src="/imgs/comment-send.gif" />');                                        
				},
			   success: function(data) {
					var parentid;
					if (data.parent_id > 0) parentid = '<p class="c-comment-reply"><strong>Ответ на комментарий </strong> <a href="#comm'+ data.parent_id + '">№'+ data.parent_id + '</a>:</p>';
					var cCommentHead = $('<div></div>').attr('class', 'c-comment-head')
									.append('<img alt="'+data.uname+'" src="http://'+location.hostname+'/files/images/users/thumb-'+data.pic+'">')
									.append('<a class="c-comment-author" href="http://'+location.hostname+'/user/'+data.uname+'">'+data.uname+'</a>')
									.append('<small class="c-comment-role">user</small>')
									.append('<small class="c-comment-date">только что</small>')
									;
					var cCommentBody = $('<div></div>').attr('class', 'c-comment-body')
									.append(parentid)
									.append(data.comment);
					var cCommentFooter = $('<div></div>').attr('class', 'c-comment-footer')
									.append('<a href="#' + data.c_id + '" name="comm' + data.c_id + '">№ ' + data.c_id + '</a>')
									.append('<a href="#"><strong>Ответить</strong></a>');
					var postcomment = $('<div></div>').attr('id', 'comm' + data.c_id).attr('class', 'c-comment')
										.append(cCommentHead)
										.append(cCommentBody)
										.append(cCommentFooter);
                                        $('#comment-send').remove();
				$(postcomment).appendTo('#allcomments').show('slow');
			   },

			   error: function(xhr, textStatus, errorThrown) {
                                $('#comment-send').remove();
                                alert('An error occurred! ' + ( errorThrown ? errorThrown : xhr.status ));
			   },

			   complete: function() {
					$('#submit-comment').attr('value', 'Добавить комментарий');
					$('#commentform textarea').val('');
					$('#commentform textarea').show('slow');
					$('#commentform input, textarea').removeAttr('disabled', 'disabled');


				}

			});
			}
			else {
				alert('А давайте писать содержательные комменатрии!');
			}
			  return false;
                  }
                });


		$('a.answer').click(function(e) {
			e.preventDefault();
			var parentid =  $(this).attr('id').replace('ans', '');
			$('#comment-parent').remove();
			$('#parent_id-element').remove();
			$('#comment-label').after('<dt id="comment-parent"><label for="comment-parent">Ответ на комментарий №<a href="#comm' + parentid + '" >' + parentid + '</a> <a id="parent-cancel" href="#" >отмена</a> </label></dt> ');
			$('#p_id-element').after('<dd id="parent_id-element"><input type="hidden" id="parent_id" value="' + parentid + '" name="parent_id"></dd>');
			$('#comment').focus();			
		});
		
		//генерация ссылки для поста
		var purl = $('#purl').val();		
		if (purl == '') {
			$('#pname').keypress(function(e) {
				var pname = $('#pname').val();
				pname = str_replace(arrRus, arrEng, pname);
				pname = pname.toLowerCase();
				pname = pname.replace(/[^-a-z0-9~\s\.:;+=_\/]/g, "");
				pname = pname.replace(/[\s\.:;=+]+/g, "-");				 
				$('#purl').val(pname);
			});
			$('#pname').change(function(e) {
				var pname = $('#pname').val();
				pname = str_replace(arrRus, arrEng, pname);
				pname = str_replace(arrRus, arrEng, pname);
				pname = pname.toLowerCase();
				pname = pname.replace(/[^-a-z0-9~\s\.:;+=_\/]/g, "");
				pname = pname.replace(/[\s\.:;=+]+/g, "-");
				$('#purl').val(pname);
			});
		}
		
//		$('#purl').change(function() {
//			alert('asdf');
//		});
            var postSortOpts = {
                items: 'ul>li',
                axis: 'y',
                update: function(e, ui) {
//                    alert('send!'); 
                }

            }
            $("#postcat").sortable(postSortOpts);
	});
