var beta = location.search && location.search=='?lol';

webcodes = {site: new Object(), options: new Object(), beautify: new Object(), highlight: new Object(), forms: new Object(), cookie: new Object(), uwnd: new Object(), user: new Object(), share: new Object(), entry: new Object(), temp: new Object()};

webcodes.site.init=function(login){
webcodes.site.ie=!+"\v1";
webcodes.user.guest=!login;
webcodes.site.moz_web=($.browser.mozilla || $.browser.safari);
$(document).ready(function(){
$('#f div.y:odd, #q li:odd').css('background','#f6f6f6');
$('textarea')[typeof opera != 'undefined' ? 'keypress': 'keydown'](function(evt) {
evt = evt || window.event;var key = evt.keyCode || evt.which,obj = this;
if (key == 9){if (obj.nodeName) if (obj.nodeName.toLowerCase() == "textarea") obj.focus();
if (document.selection){var iesel = document.selection.createRange().duplicate();iesel.text = "\t";
} else {var start = obj.selectionStart,	end = obj.selectionEnd;	var left = obj.value.substring(0, start),
right = obj.value.substring(end),scroll = obj.scrollTop;obj.value = left + "\t" + right;
obj.selectionStart = obj.selectionEnd = start + 1;obj.scrollTop = scroll;obj.focus();}
if (evt.preventDefault) evt.preventDefault();evt.returnValue = false;return false;}});});
if(!/^(w{3}\.)?[obewsedc]{8}\.[a-z]{2}$/i.test(location.hostname)){delete webcodes;}}

webcodes.cookie.add=function(name,value,days){if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));var expires="; expires="+date.toGMTString()}else var expires="";document.cookie=name+"="+value+expires+"; path=/"}

webcodes.cookie.remove=function(name){webcodes.cookie.add(name,'',-1)}

webcodes.cookie.read=function(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length)}return null}

webcodes.options.checkbox=function(){
$('#g img[alt="checkbox"]').bind('click', function(){
this.src=this.src.indexOf('un')!=-1?'/img/checked.png':'/img/unchecked.png';});
$('#g label').bind('click', function(){
var target=$(this).prev()[0];
target.src=target.src.indexOf('un')!=-1?'/img/checked.png':'/img/unchecked.png';});}

webcodes.options.type=function(){
$('#oc p a').click(function(){
var type=this.innerHTML.toLowerCase();
var input=$('#format')[0];
$(this).parent().find('a.a').removeClass('a');$(this).addClass('a');
if(type=='html' || type=='css' || type=='js'){
input.title='Переформатировать '+type+'-код для лучшего восприятия';input.disabled=false;}
else{input.title='Обработка кода для данного типа данных невозможна';input.disabled=true;}});}

webcodes.options.frames=function(){
new _uWnd('frames','Готовые каркасы',666,400,{autosizeonimages:1,resize:0},{xml:false,dataType:'html',url:'/temp/frames/index.html'});}

webcodes.options.repl=function(){
new _uWnd('replace','Замена',320,150,{autosize:0,resize:0,align:'left'},
'<div id="rl"><textarea cols="25" rows="2">Что заменяем?</textarea><textarea cols="25" rows="2">На что заменяем?</textarea><input type="checkbox" id="reg" /><label for="reg">Учитывать регистр</label><input type="button" value="Заменить" /><input type="button" value="Заменить всё" /></div>');
}

webcodes.temp.frame=function(frame){
var area = $('textarea.e');
if(!isEmpty(area.val()) && !confirm('У вас имеется введённый код.\nЕсли вы продолжите он полностью будет замёнен на код выбранного каркаса. Продолжить?')){return;}
_uWnd.close('frames');
area.attr('disabled','disabled');
frame=frame.split('.')[1].substring(22)
$.get('/temp/frames/' + frame + '.html', function(code){
var desc;code=code.replace(/\n\t<!-- (.+?) -->\n/i, function(full, incomment){
desc=incomment + '.\nПример - http://webcodes.ru/temp/frames/' + frame + '.html';return '';});
$('#g textarea').val(desc);$('#g input').val('Каркас ('+frame+')');
area.val(code).removeAttr('disabled');
$('#oc p a.a').removeClass('a');$('#oc p a:eq(1)').addClass('a');
$('#format').attr({disabled: false, title: 'Переформатировать html-код для лучшего восприятия'});})}

webcodes.highlight.init=function(type){
var target=$('#q'); webcodes.entry.code=target.clone(1);
if(!isEmpty(type) && (/^(php|js|html|css|mysql|cplusplus|csharp|delphi|java)$/i).test(type)){
target.addClass(type).chili();}else{target.html(target.html().replace(/\n/g,'<br />'));}
if($('#cm').length){webcodes.highlight.links($('#cm'));}
webcodes.highlight.nums();
webcodes.highlight.links(target);
webcodes.entry.init(type);
webcodes.share.fixClip();
webcodes.share.links();}

webcodes.highlight.links=function(obj){
var target=obj[0], code=target.innerHTML, reg=/(http:\/\/[^\s<>'",]+)/ig;
// var reg=new RegExp('(\s|\'|"|;|>|^)(http:\/\/(?!www\.w3\.org)[a-z0-9-_.#?/&=:]+;)(&|<|\s|\'|"|$)', 'ig');
if(!reg.test(code)){return;}
target.innerHTML=code.replace(reg, '<a target="_blank" href="$1">$1</a>');}

webcodes.highlight.nums=function(){var h=$("#q")[0],c=h.innerHTML,m=$.browser.msie?"<BR>":/<br[\s\/]*>/i,d=/<span[^>]+?>[\s\S]+?<\/span>/ig,j=/<span[^>]+?>/i,b=/<\/span>/i,o=/<span[^>]+?><\/span>/ig,k=/<span[^>]+?>[^>]+?<br[\s\/]*>/i,a=[],n;function f(i,p){n[p]+="</span>";while(true){p++;if(b.test(n[p])){n[p]=i+n[p];break}else{n[p]=i+n[p]+"</span>"}}}function l(i){a[i]=n[i].replace(d,"");return j.test(a[i])}n=c.split(m);if(k.test(c)){for(var e=0,g=n.length;e<g;e++){if(j.test(n[e])&&l(e)){f(a[e].match(j),e)}}}c="<ol><li>"+n.join("</li><li>")+"</li></ol>";c=c.replace(o,"");h.innerHTML=c}

webcodes.entry.init=function(type){
var data={};
data.title=$.trim($('h2:eq(0)').text());
data.brief=$('#note').text();
data.code=webcodes.entry.code.text();
data.url=location.href.split('#')[0].split('?')[0].replace('http://www.','http://');
data.type=type;webcodes.entry.data=data;}

webcodes.entry.addedOn = function (x) {
	var a = new Date(x),
	b = (((new Date()).getTime() - a.getTime()) / 1000),
	c = Math.floor(b / 86400);
	if (!isNaN(c) || !c < 0 || !c >= 31) {
		return c == 0 && (b < 60 && 'пару секунд назад' || b < 120 && '1 минуту назад' || b < 3600 && Math.floor(b / 60) + ' минут назад' || b < 7200 && '1 час назад' || b < 86400 && Math.floor(b / 3600) + ' часов назад') || c == 1 && 'вчера' || c < 7 && c + ' дней назад' || c < 31 && Math.ceil(c / 7) + ' недель назад' || c < 365 && Math.ceil(c / 31) + ' месяца назад';
	}
}

webcodes.forms.add=function(){
var text, data={title: $('#f input[type="text"]').val(), brief: $('#g textarea').val(), message: $('#f textarea:eq(1)').val(), source:webcodes.forms.getType(), aname: -$('#can_comment[src$="unchecked.png"]').length+1, ocat: -$('#is_private[src$="unchecked.png"]').length+2, jkd498: 1, jkd428: 1, a: 12, format_brief: 1, coms_allowed: 1}, target=$('#f'), top=target.offset().top, left=target.offset().left, height=target[0].offsetHeight, width=target[0].offsetWidth;
if(isEmpty(data['message'])){webcodes.uwnd.alert('Не введён код!');$('#f textarea:eq(1)').val('').focus();return;}
if(data['brief']=='Комментарий к коду'){data['brief']='';}
if(isEmpty(data['title']) || data['title']=='Название кода'){data['title']='Безымянный '+(data['source']?'код':'текст')+' от '+parseInt((new Date().getTime()/1000));}
data['message']=webcodes.forms.parseCode(data['message']);
$('input,textarea').attr('disabled', true);
$('#lg').fadeIn('slow');
/* target.animate({opacity: 0.3}, 500)*/target.after('<div id="wait" style="position:absolute;left:'+left+'px;top:'+top+'px;height:'+height+'px;width:'+width+'px"></div>');
if(webcodes.user.guest){webcodes.uwnd.secCode();}
$.get('/publ/0-0-0-0-1', function(ssid){
data['ssid']=$('input[name="ssid"]', ssid).val();
if(webcodes.user.guest){return webcodes.forms.guestadd(data, ssid);}
$.post('/publ/', data, function(xml){text=$(xml).text();
if(text.indexOf('успешно')!=-1){
location.href = '/'+text.match(/publ\/\d+\-\d+\-\d+\-\d+/).toString();}
else{webcodes.uwnd.alert('Ошибка');}
});
});
}

webcodes.forms.guestadd=function(data,tpl){
var img=$('#secImg', tpl).clone(1), target=$('#seccode').empty().css('background',''), input=$('<input type="text" maxlength="4" style="padding: 5px;height:13px;margin-top:1px;width:40px;" />').keyup(function(){
this.value=this.value.replace(/\D*/g,'');
if(this.value.length==4){
_uWnd.setTitle('seccode', 'Идёт добавление кода...')
$('#seccode').empty().css('background','url(/.s/img/wd/3/ajax.gif) no-repeat center');
var data=webcodes.entry.data, text;data['code']=this.value;
$.post('/publ/', data, function(xml){
text=$(xml).text();if(text.indexOf('успешно')!=-1){
location.href = '/'+text.match(/publ\/\d+\-\d+\-\d+\-\d+/).toString();}
else{webcodes.forms.add();}});}});
target.append(img).append(' ').append(input);input.focus();
data['seckey']=$('input[name="seckey"]', tpl).val();data['ocat']=1;webcodes.entry.data=data;}

webcodes.forms.loadEdit=function(id){
var target=$('#code'), left=target.offset().left, top=target.offset().top, height=target[0].offsetHeight, width=target[0].offsetWidth, screen=document.documentElement.clientHeight, divHeight=screen-top;
webcodes.entry.data.id=id;
$('#ZeroClipboardMovie_1').parent().hide();
target.after('<div id="wait" style="z-index:667;position:absolute;left:'+left+'px;top:'+top+'px;height:'+divHeight+'px;width:'+width+'px;background:url(/.s/img/wd/3/ajax.gif) no-repeat center;"></div>').fadeOut('fast', function(){
$('#wait')[0].style.position='static';
$.get('/publ/0-0-0-'+id+'-13-1', function(data){
$('#edit_area textarea:eq(1)').val(webcodes.forms.deParseCode($('textarea[name="message"]', data).val()));
$('#g input[type="text"]').val($('input[name="title"]', data).val());
$('#g textarea').val($('textarea[name="brief"]', data).val());
$('#oc p a').eq(webcodes.forms.getType($('input[name="source"]', data).val())).addClass('a');
$('#oc input[type="button"]:last')[0].disabled=!(/^html|js|css$/i.test($('#oc a.a').text()));
$('#oc input[type="button"]:last')[0].title=(/^html|js|css$/i.test($('#oc a.a').text())?'Переформатировать '+$('#oc a.a').text().toLowerCase()+'-код для лучшего восприятия':'Обработка кода для данного типа данных невозможна');
$('#can_comment').attr('src', '/img/'+($('input[name="aname"]', data).val()==='0'?'un':'')+'checked.png');
$('#is_private').attr('src', '/img/'+($('#cus1:checked', data).length==1?'un':'')+'checked.png');
$('#edit_area').fadeIn('normal');
$('#wait').css('position', 'absolute').fadeOut('fast');
});
});
}

webcodes.forms.savedit=function(){
var data={title: $('#g input[type="text"]').val(), brief: $('#g textarea').val(), message: $('#edit_area textarea:eq(1)').val(), source: webcodes.forms.getType(), aname: -$('#can_comment[src$="unchecked.png"]').length+1, ocat: -$('#is_private[src$="unchecked.png"]').length+2, jkd498: 1, jkd428: 1, a: 14, id: webcodes.entry.data.id, format_brief: 1, coms_allowed: 1};
if(isEmpty(data['message'])){return alert('Не введён код');}
if(isEmpty(data['title']) || data['title']=='Название кода'){data['title']='Безымянный '+(data['source']?'код':'текст')+' от '+parseInt((new Date().getTime()/1000));}
data['message']=webcodes.forms.parseCode(data['message']);
$('#edit_area').animate({opacity: 0.3}, 500);
$('#wait').show();
$.get('/publ/0-0-0-'+data['id']+'-13-1', function(ssid){
data['ssid']=data['ssid']=$('input[name="ssid"]', ssid).val();
$.post('/publ/', data, function(xml){
window.location.reload(true);});});}

webcodes.forms.getType=function(b){var c=['html','js','css','php','mysql','cplusplus','csharp','delphi','java'];if(!b){var d=$('#oc p a.a').text().toLowerCase().replace('c++','cplusplus').replace('c#','csharp');return d==='text'?'':d}for(var a=0;a<c.length;a++){if(c[a]===b){return(a+1)}}return 0}

webcodes.forms.stopEdit=function(){
$('#edit_area').fadeOut('normal', function(){
$('#code').fadeIn('normal');
$('#ZeroClipboardMovie_1').parent().show();
$('#wait').css('position', 'absolute').fadeOut('fast', function(){
$(this).remove();
});
});
$('#wait').show();}

webcodes.forms.parseCode=function(code){
code=code.replace(/&/g,'&amp;');
code=code.replace(/\t/g,'&#9;');
code=code.replace(/\u00a0|\u0020/g,'&#32;');
return code;}

webcodes.forms.deParseCode=function(code){
code=code.replace(/&lt;/g,'<');
code=code.replace(/&gt;/g,'>');
code=code.replace(/&#92;/g,'\\');
code=code.replace(/&#9;/g,'\t');
code=code.replace(/&#32;|&nbsp;/g,' ');
code=code.replace(/&amp;/g,'&');
return code;}

webcodes.forms.remove=function(a){
var char=($.browser.mozilla?'"':"'"), id = (!a)?'':a;
if(confirm('Удалить?')){
$.get($('#mod'+id+' img[title="Удалить"]').parent().attr('onclick').toString().split(char)[3], function(){
if(!a){location.href = (document.referrer.indexOf(location.host)!=-1)?document.referrer:'http://'+location.host;} else {$('#e'+a).fadeOut('fast')}});}}

webcodes.forms.clone=function(){
var code=webcodes.forms.parseCode(webcodes.entry.code.text()), type=webcodes.entry.data.type, title='Копия: '+webcodes.entry.data.title, brief=webcodes.entry.data.brief, target=$('#copy_to_mycodes_span');
target.find('img').attr('src', '/.s/img/wd/3/ajaxs.gif');
$.get('/publ/0-0-0-0-1', function(data){
var ssid=$('input[name="ssid"]', data).val();
$.post('/publ/', {jkd498: 1, jkd428: 1, ocat: 2, title: title, brief: brief, format_brief: 1, message: code, source: type, coms_allowed: 1, a: 12, ssid: ssid}, function(xml){
var text=$(xml).text();var complink='/'+text.match(/publ\/\d+\-\d+\-\d+\-\d+/).toString();
if(text.indexOf('успешно')!=-1){location.href = complink;}else{
webcodes.uwnd.alert('Ошибка o___6!');target.find('img').attr('src', '/.s/img/icon/er.png');}});});}

webcodes.forms.init=function(){
if (location.hash == '#getCode') {$('textarea.e').val(window.name)}}

webcodes.share.links=function(){
var actions={'Получить код': webcodes.share.htmlcode, 'Сохранить к себе': webcodes.forms.clone, 'Ссылки': webcodes.uwnd.links};
$('#ut div.r span').each(function(){
if(actions[$(this).text()]){this.onclick=actions[$(this).text()];}});}

webcodes.share.htmlcode=function(){
var css = webcodes.share.cssRules(), code = $('#q').html(), styles = [], num;
css = css.toLowerCase().replace(/\s/g,'').replace(/\.([a-z_0-9-]+)\{(.+?)\}/ig, function (all, theClass, attrs) {styles[theClass] = attrs; return '';});
code = code.replace(/<span class=(")?([a-z_0-9-]+)\1>([\s\S]+?)<\/span>/ig, function (all, quote, theClass, content) {
return '<span style="' + styles[theClass] + '">' + content + '</span>';
}).replace(/<a target="_blank" href="(.+?)">(.+?)<\/a>/ig, function (all, href, content) {return '<a href="' + href + '" target="_blank" rel="nofollow">' + content + '</a>';
}).replace(/<li>|<ol>|<\/li>|<\/ol>/ig, function(tag){
return tag.toLowerCase();
}).replace(/\t/g, '&#9;').replace(/<li[^>]+?>/ig,'<li>').replace(/<li><\/li>/ig,'<li>&nbsp;</li>').replace(/<span style="([^>]+)">([^>]+?)<\/span><span style="\1">([^>]+?)<\/span>/ig, '<span style="$1">$2$3</span>').replace('<ol>', '<ol style="border-left:3px solid grey;padding:5px 5px 5px 50px;">');
code='<pre style="font-size:9pt;font-family:\'courier new\';line-height:11pt;overflow-x:auto">'+code+'</pre>';
num=code.length;num=[num, num.toString()];
if(num[0]%10==1 && num[1].substr(-2)!='11'){text='';}
else if(num[0]>21 && (num[0]%10)>1 && (num[0]%10)<5){text='а';}else{text='ов';}
webcodes.uwnd.htmlcode(code, num[1], text);}

webcodes.share.cssRules=function(){
if(!$.browser.msie){return $('style.highlight-style').text();}
var target=$('style.highlight-style'), num = target.length, code='';
for(var i=0;i<num;i++){code+=target[i].innerHTML;}
return code;}

webcodes.share.clipboard=function(){
clip=new ZeroClipboard.Client();
clip.setHandCursor(true);
clip.addEventListener('complete', function(){webcodes.uwnd.alert('Код скопирован в буффер обмена.');});
clip.addEventListener('load', function(){
var code=webcodes.entry.data.code;
code=code.replace(/\n/g,'\r\n');
code=code.replace(/\u00a0/g,' ');
clip.setText(code);clip.reposition();});
clip.glue('copy_to_clipboard_span');}

webcodes.share.fixClip = function(){
if(!/\\"/.test(webcodes.entry.data.code)){return;}
document.onmouseup = function(e){
e = e || window.event;
var target = e.target || e.srcElement;
if(target.nodeName == 'EMBED' || target.nodeName == 'OBJECT'){
webcodes.uwnd.alert('Код скопирован в буффер обмена.');}}}

webcodes.uwnd.alert=function(text){_uWnd.alert(text, 'Информация', {w: 250, h: 75});}

webcodes.uwnd.profile=function(uname){
new _uWnd('profile',uname,500,250,{autosize:1,icon:'/img/22.png'},{xml: false, dataType:'html', url:'/index/8-0-'+uname.replace(/-/g,'~')+'/'});}

webcodes.uwnd.reg=function(){
new _uWnd('reg','Регистрация нового профиля',600,440,{autosize:0,icon:'/img/22.png'},'<iframe scrolling="no" src="/index/3-1" style="border: 0; width: 100%; height: 100%;"></iframe>');}

webcodes.uwnd.firstLogin=function(){
_uWnd.close('reg');
openLayerB('LF',0,'/index/40','Login',250,130,1);}

webcodes.uwnd.secCode=function(){
new _uWnd('seccode','Введите код безопасности',200,30,{align:'left',maxw:200,minh:30,nomove:1,resize:0,onbeforeclose:function(){$('#f').animate({opacity: 1}, 500);$('#wait').remove();$('#lg').fadeOut('fast');$('input,textarea').removeAttr('disabled')}},'<div id="seccode" style="height:100%;width:100%;background:url(/.s/img/wd/3/ajax.gif) no-repeat center;"></div>');
_uWnd.setTitle('seccode', 'Введите код безопасности');}

webcodes.uwnd.wait=function(){webcodes.uwnd.alert('Дождитесь полной загрузки страницы.');}

webcodes.uwnd.htmlcode=function(code,num,text){
var attrs=webcodes.site.moz_web?'cols="49" rows="9"':'cols="50" rows="10"';
code=code.replace(/&/g,'&amp;');
new _uWnd('htmlcode',' HTML-Код ('+num+' символ'+text+')',400,200,{icon: '/.s/img/icon/code.png', autosize: 0, shadow: 1, resize: 0, alert: 1, oncontent: function(){$('textarea:first').select().focus();}},'<textarea wrap="hard" '+attrs+'>' + code + '</textarea>');}

webcodes.uwnd.links=function(){
new _uWnd('links',' Ссылки на код', 250, 60, {icon: 'http://alexeenko.org/images/icons/globe.png', resize: 0},
'<input type="text" onclick="this.select();" style="width: 250px" value="[url='+webcodes.entry.data.url+']'+webcodes.entry.data.title+'[/url]" /><br /><input onclick="this.select();" type="text" style="margin-top: 5px; width: 250px" value=\'<a href="'+webcodes.entry.data.url+'" target="_blank">'+webcodes.entry.data.title+'</a>\' />');
}

function replaceText(d,j,k){var g=/<([a-z]+)(.*?)>(.*?)<\/\1>/ig;var e=/<[a-z]+.*?\/?>/ig;var a=Math.random().toString().slice(2);var h=[];function f(i){return g.test(i)||e.test(i)}function b(i){i=i.replace(g,function(n,m,o,l){if(f(l)){l=b(l)}return a+(h.push("<"+m+o+">"+l.replace(j,k)+"</"+m+">")).toString()});i=i.replace(e,function(l){return a+(h.push(l)).toString()});return i}if(!f(d)){return d.replace(j,k)}d=b(d);d=d.replace(j,k);for(var c=h.length;c>-1;c--){d=d.replace(a+(c+1).toString(),h[c])}return d};

function htmlspecialchars(code){return code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');}

function setCaretTo(a,b){if(a.createTextRange){var c=a.createTextRange();c.move("character",b);c.select()}else if(a.selectionStart){a.focus();a.setSelectionRange(b,b)}};

function isEmpty(data){return /^\s*$/.test(data);}