function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}
		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }
		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }
		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		 if (str.indexOf(" ")!=-1){
		    return false
		 }
 		 return true
}
function add_comment(pid, hash) {
	var old = $('#commentlist').html();
	if($('#username').val().length==0) {
	alert('Ошибка: Вы не указали свое имя!');
	return false;
	}
	if($('#usermail').val().length==0) {
	alert('Ошибка: Вы не указали свой E-mail!');
	return false;
	}
	if($('#usercomment').val().length==0) {
	alert('Ошибка: Вы не ввели комментарий!');
	return false;
	}
	if(!echeck($('#usermail').val())) {
	alert('Ошибка: Вы неверно указали свой E-mail!');
	return false;
	}
	var author = $('#username').val();
	var author_email = $('#usermail').val();
	var author_url = $('#usersite').val();
	var content = $('#usercomment').val();
	var info = '<div class="message-box comment-info">Ваш комментарий успешно добавлен и после проверки администратором появится здесь.</div>';
   	$('#commentlist').html('<center><img src="/images/template/loader.gif" alt="Загрузка"></center>' + old);
	var req = new JsHttpRequest();
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT become responseJS).
            $('#commentlist').html(req.responseText + old);
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/ajax.php', true);
    // Send data to backend.
    req.send( { action: 'comment_add', pid: pid, hash: hash, author: author, author_email: author_email, author_url: author_url, content: content } );
}
function rate(id, rating, table) {
	var req = new JsHttpRequest();
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT become responseJS).
            document.getElementById('unit_long'+id+'').innerHTML = req.responseText;
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/ajax.php', true);
    // Send data to backend.
    req.send( { id: id, rating: rating, table: table, action: 'rate' } );
}

function subscribe() {
    var email = $('#sub_mail').val();
	var req = new JsHttpRequest();
    // Code automatically called on load finishing.
	$('#subscribe_info').show();
	$('#subscribe_info').html('<center><img src="/images/template/loader.gif" alt="Загрузка"></center>');
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT become responseJS).
            document.getElementById('subscribe_info').innerHTML = req.responseText;
			$('#subscribe_info').animate({opacity: 1.0}, 3000).hide("slow");
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/ajax.php', true);
    // Send data to backend.
    req.send( { email: email, action: 'subscribe' } );
}
function unsubscribe() {
    var email = $('#sub_mail').val();
	var req = new JsHttpRequest();
    // Code automatically called on load finishing.
	$('#subscribe_info').show();
	$('#subscribe_info').html('<center><img src="/images/template/loader.gif" alt="Загрузка"></center>');
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            // Write result to page element (_RESULT become responseJS).
            document.getElementById('subscribe_info').innerHTML = req.responseText;
			$('#subscribe_info').animate({opacity: 1.0}, 3000).hide("slow");
        }
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/ajax.php', true);
    // Send data to backend.
    req.send( { email: email, action: 'unsubscribe' } );
}
/**
 *
 * @access public
 * @return void
 **/
function panel(id){
	for(var i=1; i<6; i++) {
	$('#panel_' + i).hide();
	$('#panel_' + id + '').show('fast');
	}
}
/**
 *
 * @access public
 * @return void
 **/
function  setmail() {
	$.cookie("shop_email", document.getElementById('shop_email').value, { path: '/shop', expires: 365 });
}

function padLeft(string, width) {
  var padded = string;
  var needed = width - string.length;
  for (var i=0; i<needed; i++) {
    padded = " " + padded;
  }
  return padded;
}

function addLineNumbers(lineArray, start) {
  var currentLine = start;
  var maxLine = start + lineArray.length - 1;
  var lnWidth = maxLine.toString().length;
  var numberedLineArray = [];
  for (var i=0; i<lineArray.length; i++) {
    numberedLineArray.push('<span class="ln">' + padLeft(currentLine.toString(), lnWidth) + '  </span>' + lineArray[i]);
    currentLine++;
  }
  return numberedLineArray;
}

function styleCode() {
  // IE wouldn't work with early versions of this function, so I stopped trying
  // to get it to work. Now that the function's been rewritten, I may need to
  // revisit this decision.
  var isIE = navigator.appName.indexOf('Microsoft') != -1;
  if (isIE) return;

  // Go through each of the <pre><code> blocks.
  $('pre code').each( function(i, elem) {
    var oldContent = elem.innerHTML;
    var newContent = [];

    // Get the language, if it's given, and remove it.
    var lang = oldContent.match(/^(bash|cmake|cpp|css|diff|xml|html|ini|java |javascript|lisp|lua|perl|php|python|ruby|scala|sql|tex):\n/);
    if (lang) {
      lang = lang[1];
      oldContent = oldContent.split("\n").slice(1).join("\n");
    }

    // Get the starting line number, if it's given, and remove the line numbers.
    var line = oldContent.match(/^( *)(\d+):(  )/);
    if (line) {
      line = parseInt(line[2]);
      oldContent = oldContent.replace(/^( *)(\d+):(  )/mg, "");
    }

    // Remove trailing empty lines, if any.
    oldContent = oldContent.replace(/\n+$/, "");

    // Put the unnumbered code back into the element.
    elem.innerHTML = oldContent;

    // Highlight the code if the language is given.
    if (lang) {
      $(this).addClass("language-" + lang);
      hljs.highlightBlock(elem);
    }

    // Put the line numbers back in if they were removed.
    if (line) {
      var newContent = elem.innerHTML.split("\n");
      newContent = addLineNumbers(newContent, line);
      newContent.push("");
      newContent.push('<button onclick="showPlain(this.parentNode)">Plain code</button>');
      elem.innerHTML = newContent.join("\n");
    }

  })
}

function showPlain(code) {
  var oldCode = code.cloneNode(true);
  for (var i=0; i<oldCode.childNodes.length; i++){
    node = oldCode.childNodes[i];
    if (node.nodeName == 'SPAN' || node.nodeName == 'BUTTON'){
      oldCode.removeChild(node);
    }
  }
  var w = window.open("", "", "width=800,height=500,resizable=yes,scrollbars=yes");
  var d = w.document;
  d.open();
  d.write("<html><head><title>Code</title></head><body><pre><code>", oldCode.innerHTML, "</code></pre></body></html>");
  d.close();
}

//$(document).ready(function() {
	//initHighlighting();
//});

$(document).ready(function(){

        // Initialise highlighting
        if($('pre').length){
                $('pre').each(function(){
                        highLight($(this));
                });
        }

});

// Highlight item
function highLight(thisItem){
        snippet  = thisItem.html();
        snippet = snippet.replace(/&amp;/ig, '&amp;amp;');
        snippet = snippet.replace(/&amp;amp;/ig, escape('&'));
        snippet = snippet.replace(/&lt;/ig, '<');
        snippet = snippet.replace(/&gt;/ig, '>');
        language = thisItem.attr('class');
        $.ajax({
                type: "POST",
                url: '/highlight.php',
                data: 'language='+language+'&snippet='+snippet,
                dataType: "html",
                success: function(msg){
                        if (msg){
                                msg = msg.replace('&amp;', '&');
                                thisItem.after(msg);
                                thisItem.hide();
                        }
                }
        });
}
