var hfont = { src: site_root+'/helvetica.swf', wmode: 'transparent' };
sIFR.activate(hfont);
sIFR.replace(hfont, { selector: 'h1, h2',
	css: ['.sIFR-root { color: #15779b }', 'a { color: #15779b; text-decoration: none; }','.span { font-size: 50% }']
});
//setTimeout('checksifr()',2000);

function checksifr(){
	$$('.sIFR-replaced').each(function(h){ if(h.getHeight()==0) h.update(h.lastChild.innerHTML); });
}

function cool_alert(msgs) {
	if(!msgs)
		return;
	if(msgs instanceof Array)
		msgs=msgs.join('<br/>');
	if(msgs=='')
		return;
	msgs=msgs.replace('\n','<br/>');
	$('overlay').style.display='block';
	$('lightbox').style.marginTop='-20px';
	$('lightbox').style.display='block';
	$('lbLoadMessage').style.display='none';
	var d=new Element('div', {id:'lbContent', 'class':'pop_foot', style:'display:none'});
	var t=new Element('table');
	var tr=new Element('tr');
	var td=new Element('td');
	td.insert(new Element('img', {src: site_dir+'/images/pop_attention.gif'}));
	tr.insert(td);
	td=new Element('td').update(msgs);
	d.onclick=function(e){cool_alert_close();};
	tr.insert(td);
	t.insert(tr);
	d.insert(t);
	$('lightbox').insert(d);
	new Effect.SlideDown('lbContent');
	Event.observe(window,'keyup', cool_alert_close_esc.bindAsEventListener(this));
}

function cool_alert_close() {
	new Effect.Fold('lbContent');
	$('overlay').style.display='none';
	$('lightbox').style.display='none';
	$('lightbox').style.marginTop='-240px';
}

function cool_alert_close_esc(e) {
	if (e.keyCode == Event.KEY_ESC)
		cool_alert_close();
}

function rate_init(rc,rating) {
	rc.update('');
	if(rating>=0 && rating<=5){
		var startype;
		var rateid=rc.id.substr(7);
		for(var i=0;i<5;i++){
			if(rating>=1){
				startype='on';
				rating--;
			}
			else if(rating>=0.4){
				startype='half';
				rating=0;
			}
			else
				startype='off';
			var star=new Element('img',
				{ id: 'star-'+rateid+'-'+i, src: site_dir+'/images/rating_'+startype+'.gif', 'class': startype }
			);
			if(rc.getAttribute('rel')!='rated'){
				star.onmouseover=new Function("evt", "rate_hover("+rateid+", "+i+");");
				star.onmouseout=new Function("evt", "rate_normal("+rateid+", "+i+");");
				star.onclick=new Function("evt", "rate_click('"+rc.getAttribute('rel')+"', "+rateid+", "+i+");");
			}
			rc.insert(star);
		}
	}
}

function rate_hover(rateid,rate) {
	for(var j=0;j<=rate;j++)
		$('star-'+rateid+'-'+j).src=site_dir+'/images/rating_over.gif';
}

function rate_normal(rateid,rate) {
	for(var j=0;j<=rate;j++)
		$('star-'+rateid+'-'+j).src=site_dir+'/images/rating_'+$('star-'+rateid+'-'+j).className+'.gif';
}

function rate_click(mode,rateid,rate) {
	new Ajax.Request(get_href(mode,'rate'), {
		method: 'post',
		parameters: {'id': rateid, rating: rate+1, js: 1 },
		onSuccess: function(tr) {
			if(tr.responseJSON.rating>0){
				$('rating-'+rateid).setAttribute('rel','rated');
				$('rating-text-'+rateid).update(
					'('+tr.responseJSON.rate_count+' rating'+((tr.responseJSON.rate_count%10==1) ? '' : 's')+')'
				);
				rate_init($('rating-'+rateid),tr.responseJSON.rating)
			}
			cool_alert(tr.responseJSON.msg);
		}
	});
}

function ctrl_enter(e, form) {
	if (((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey == true)) form.submit();
}

function fblur (ftext, fid) {
	if ($(fid).value == '')
		$(fid).value = ftext
}

function ajax_post(mode,form_id,scripts) {
	if(typeof(window['tinyMCE'])!='undefined')
		tinyMCE.triggerSave();
	new Ajax.Updater('result',get_href(mode,'js'), {
	    parameters: $(form_id).serialize(),
	    method: 'post',
    	evalScripts: scripts
	});
}

function change_post_type(type) {
	var type2=(type=='text') ? 'works' : 'text';
	$('m_'+type).className='on';
	$('m_'+type2).className='';
	$('hmode').value=type;
	$('postform').action=get_href(type,'add');
	var fdiv=$('fields');
	var desc=($('abstract')) ? $F('abstract') : $F('desc');
	var sh=($('short')) ? $F('short') : '';
	fdiv.childElements().invoke('remove');
	if(type=='text'){
		fdiv.insert(new Element('div', {'class':'label'}).update('Abstract: (<a href="javascript:toggleEditor(\'abstract\')">rich editor</a>)'));
		fdiv.insert(new Element('textarea', {name: 'abstract', id: 'abstract', rows: 5}).update(desc));
		fdiv.insert(new Element('div', {'class':'label'}).update('Full text: (<a href="javascript:toggleEditor(\'text\')">rich editor</a>)'));
		fdiv.insert(new Element('textarea', {name: 'text', rows: 15}));
	}
	else {
		fdiv.insert(new Element('div', {'class':'label'}).update('Short description:'));
		fdiv.insert(new Element('input', {'type':'text', id:'short', 'name':'short', 'style':'width: 480px'}).update(sh));
		fdiv.insert(new Element('div', {'class':'label'}).update('Description: (<a href="javascript:toggleEditor(\'desc\')">rich editor</a>)'));
		fdiv.insert(new Element('textarea', {name: 'desc', id: 'desc', rows: 15}).update(desc));
	}
}

cropObj=null;

function onEndCrop(coords,dimensions ){
	$('x1').value = coords.x1;
	$('y1').value = coords.y1;
	$('x2').value = coords.x2;
	$('y2').value = coords.y2;
}

function new_cropper() {
	$('pic_loader_img').remove();
	cropObj=new Cropper.Img( 'pic_img', {
		ratioDim: { x: picw, y: pich },
		minWidth: 1, minHeight: 1,
		displayOnInit: true,
		onEndCrop: onEndCrop
	});
	//$('fileframe').hide();
}

function new_av_cropper() { // :(
	cropObj=new Cropper.Img( 'pic_img', {
		ratioDim: { x: avatar_max_w, y: avatar_max_h },
		minWidth: avatar_min_w, minHeight: avatar_min_h,
		displayOnInit: true,
		onEndCrop: onEndCrop
	});
}

function change_croppable_pic(s) {
	if(cropObj!=null){
		cropObj.remove();
		cropObj=null;
	}
	$('pic_img').show();
	$('pic_img').src=s;
}

function show_loading(target) {
	$(target).insert(new Element('img', {id:'pic_loader_img', src:site_dir+'/images/loading.gif' }));
}

function show_image_form(pdiv,post_id,mode) {
	pdiv.childElements().invoke('remove');
	$('formact').value='crop'; // upload
	pdiv.insert(new Element('input', {type: 'hidden', name: 'id', id: 'post_id', value: post_id }));
	pdiv.insert(new Element('input', {type: 'hidden', name: 'x1', id: 'x1' }));
	pdiv.insert(new Element('input', {type: 'hidden', name: 'x2', id: 'x2' }));
	pdiv.insert(new Element('input', {type: 'hidden', name: 'y1', id: 'y1' }));
	pdiv.insert(new Element('input', {type: 'hidden', name: 'y2', id: 'y2' }));
	pdiv.insert(new Element('div', {'class': 'label'}).update('Thumbnail Image:'));
	thumbdiv=new Element('div', {id: 'pic_thumb', style: 'float:left;'});
	thumbdiv.insert(new Element('img', {'class': 'pic_frame', src: site_dir+'/images/pop_thumb.png'}));
	pdiv.insert(thumbdiv);
	pdiv.insert(new Element('iframe', {
	src: get_href('post_img','-', post_id)+((rewrite) ? '?' : '&')+'type='+mode, id: 'fileframe',
		'width': 300, 'height': 140, 'frameborder': 0
	}));
	pdiv.insert(new Element('img', {id: 'pic_img', 'class': 'pic_frame' /*, src:'images/pop_pic.png'*/ }));
	$('pic_img').observe('load', new_cropper);
	$('pic_img').hide();
	pdiv.insert(new Element('a', { href: get_href(mode,'next', post_id), id: 'a_next', 'class': 'gray_box' }).update('Next Image'));
	pdiv.insert(new Element('input', {type: 'submit', 'class': 'submit', value: 'Finish', id:'pic_submit' }));
	pdiv.insert(new Element('a', { href: get_href(mode,'cancel', post_id), id: 'a_cancel', 'class': 'gray_box' }).update('Cancel'));
	$('a_next').onclick=function(){ $('uploadnext').value=1; post_submit(); return(false); }
	$('pic_submit').onclick=function(){ $('uploadnext').value=0; }
	$('a_cancel').onclick=function(){return confirm('Are you sure?');}
	$('lightbox').scrollTop=0;
}

function post_submit() {
	var mode=$F('hmode');
	var pdiv=$('pop_main');
	if(mode=='text'){
		picw=postpic_w;
		pich=postpic_h;
	}
	else {
		picw=workpic_w;
		pich=workpic_h;
	}
	if(typeof(window['tinyMCE'])!='undefined')
		tinyMCE.triggerSave();
	if($F('formact')=='add' || $F('uploadnext')==1) {
		new Ajax.Request(get_href(mode,'add'), {
		    parameters: $('postform').serialize(),
		    method: 'post',
	    	onFailure: function(tr){
	    		cool_alert('Error code: ' + tr.status + '\n\n'+tr.responseText);
	    	},
	    	onSuccess: function(tr){
	    		if(tr.responseJSON.err){
	    			alert(tr.responseJSON.err);
	    			return;
	    		}
	    		show_image_form(pdiv,tr.responseJSON.post_id,mode);
	    	}
		});
	}
	else // crop
		new Ajax.Updater('result', get_href(mode,'add'), {
		    parameters: $('postform').serialize(),
		    method: 'post',
	    	evalScripts: true
		});
}

function swap_tag(tag) {
	var inp=$('tags_input');
	if(inp){
		tags=(inp.value.strip().empty())
			? new Array()
			: inp.value.strip().split(',');
		tags=tags.invoke('strip');
		if(tags.indexOf(tag)!=-1)
			tags=tags.without(tag);
		else
			tags.push(tag);
		inp.value=tags.join(', ');
	}
}

document.observe("dom:loaded", function(event) {
	$$('.e_confirm').each(function(a){ a.onclick=function(){return confirm('Are you sure?');} });
	$$('.rating').each(function(rc){
		var rating=parseFloat(rc.innerHTML);
		rate_init(rc,rating);
	});
});