function getName(str){
	var f = str.split('@')[0];
	f = f.replace(/[\d\._-]/g,' ');
	f = f.replace(/^\s+|\s+$/g, '');
	f = f.replace(/\s+/g, ' ');
	var name_parts = f.split(' ');
	
	for(var j=0; j < name_parts.length; j++){
		name_parts[j] = (name_parts[j].substring(0,1)).toUpperCase() + (name_parts[j].substring(1,name_parts[j].length)).toLowerCase();
	}
	return name_parts.length?name_parts.join(' '):str.split('@')[0];
}

function checkMail(x){
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) return true;
	else return false;
}

function checkCreateBlogList(){
	if(!trim($('title').value).length){
		alert('Pealkiri seadmata!');
		$('title').focus();
		return false;
	}
	return true;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function checkRegister(form){
	if(!checkMail($('page-email').value)){
		alert('Vigane e-posti aadress');
		$('page-email').focus();
		return false;
	}
	if(!$('page-password').value.length){
		alert('Parooli pole määratud!');
		$('page-password').focus();
		return false;
	}
	if(!$('page-password2').value.length){
		alert('Parooli pole määratud!');
		$('page-password2').focus();
		return false;
	}
	if($('page-password').value!=$('page-password2').value){
		alert('Paroolid ei kattu!');
		$('page-password').focus();
		return false;
	}
	return true;
}

function checkEdituser(form){
	if(!checkMail($('page-email').value)){
		alert('Vigane e-posti aadress');
		$('page-email').focus();
		return false;
	}
	if($('page-password').value.length || $('page-password2').value.length){
		if(!$('page-password').value.length){
			alert('Parooli pole määratud!');
			$('page-password').focus();
			return false;
		}
		if(!$('page-password2').value.length){
			alert('Parooli pole määratud!');
			$('page-password2').focus();
			return false;
		}
		if($('page-password').value!=$('page-password2').value){
			alert('Paroolid ei kattu!');
			$('page-password').focus();
			return false;
		}
	}
	return true;
}

var curPage=0;
var curChannel=0;

function paintUued(objects){
	if(curPage<=0)
		$('tagasi').style.visibility='hidden';
	else
		$('tagasi').style.visibility='visible';
	if(curPage>=objects.info.pages-1)
		$('edasi').style.visibility='hidden';
	else
		$('edasi').style.visibility='visible';
	var current = 0;
	$('numbers-not-enough').select('li').each(function(s){
		if(objects.posts.length>current){
			s.show();
			var link = s.down('[class~=post-favicon]');
			link.src = objects.posts[current].favicon;
			var link = s.down('[class~=post-postlink]');
			link.href = objects.posts[current].url;
			link.update(objects.posts[current].title);
			var link = s.down('[class~=post-author]');
			link.update(objects.posts[current].author);
			var link = s.down('[class~=post-bloglink]');
			link.href = objects.posts[current].blog_url;
			link.update(objects.posts[current].blog_name);
			var link = s.down('[class~=post-preview]');
			link.down('span').update(objects.posts[current].contents);
			link.down('img').src=objects.posts[current].img;
		}else
			s.hide();
		current++;
	});
		
	$$('span[class~=spinner]').each(function(t){
		t.style.visibility='hidden';
	});
	window.scroll(0,$('numbers-not-enough').down('li').cumulativeOffset().top-3);
}

function removeFromList(channel, blog){
	if(!confirm('Kas soovid tõepoolest antud blogi listist eemaldada?'))
		return;
	$('blog_'+blog).fade();
	var myAjax = new Ajax.Request('/scripts/remove-from-list.py',{
		method: 'post',
		postBody: "channel="+encodeURIComponent(channel)+'&blog='+encodeURIComponent(blog),
		onComplete: function(response){
			if(response.responseText!='ok'){
				alert('Ilmnes viga, proovi uuesti!');
				$('blog_'+blog).appear();
			}
		}
	});
}


function removeFromMyList(blog){
	if(!confirm('Kas soovid tõepoolest antud blogi listist eemaldada?'))
		return;
	$('blog_'+blog).fade();
	var myAjax = new Ajax.Request('/scripts/remove-from-profile.py',{
		method: 'post',
		postBody: 'blog='+encodeURIComponent(blog),
		onComplete: function(response){
			if(response.responseText!='ok'){
				alert('Ilmnes viga, proovi uuesti!');
				$('blog_'+blog).appear();
			}
		}
	});
}

function checkNewPosts(blog, row){
	var t = $(row).up('span');
	t.hide();
	t.next('span').show();
	var myAjax = new Ajax.Request('/scripts/add-queue.py',{
		method: 'post',
		postBody: 'blog='+encodeURIComponent(blog),
		onComplete: function(response){
			alert('Blogi on lisatud kontrollimisjärjekorda, vaata mõne aja pärast uuesti.');
			t.show();
			t.next('span').hide();
		}
	});
}

function setTick(tick, blog, row){
	var t = $(row).up('span');
	t.hide();
	t.next('span').show();
	var myAjax = new Ajax.Request('/scripts/set-tick.py',{
		method: 'post',
		postBody: 'blog='+encodeURIComponent(blog)+'&skip='+(tick?0:1),
		onComplete: function(response){
			if(tick)
				t.down('a').innerHTML = "<img src=\"/images/tick_circle_frame.png\"  title=\"See blogi on aktiivne - blogi uusi postitusi kontrollitakse (kliki muutmiseks)\" alt=\"feed\" onclick=\"setTick(false,"+blog+", $(this).up('a'))\"  />";
			else
				t.down('a').innerHTML = "<img src=\"/images/cross_circle_frame.png\"  title=\"See blogi pole aktiivne - blogi uusi postitusi ei kontrollita (kliki muutmiseks)\" alt=\"feed\" onclick=\"setTick(true,"+blog+", $(this).up('a'))\"  />";
			t.show();
			t.next('span').hide();
		}
	});
}

function uuedTagasi(channel){
	curPage--;
	$$('span[class~=spinner]').each(function(t){
		t.style.visibility='visible';
	});
	var myAjax = new Ajax.Request('/scripts/get-posts.py',{
		method: 'post',
		postBody: "page="+encodeURIComponent(curPage)+'&channel='+encodeURIComponent(channel),
		onComplete: function(response){
			var objects = response.responseText.evalJSON();
			paintUued(objects);
		}
	});
}
function uuedEdasi(channel){
	curPage++;
	$$('span[class~=spinner]').each(function(t){
		t.style.visibility='visible';
	});
	
	var myAjax = new Ajax.Request('/scripts/get-posts.py',{
		method: 'post',
		postBody: "page="+encodeURIComponent(curPage)+'&channel='+encodeURIComponent(channel),
		onComplete: function(response){
			var objects = response.responseText.evalJSON();
			paintUued(objects);
		}
	});
}

function refreshUued(channel){
	curPage = 0;
		$$('span[class~=spinner]').each(function(t){
		t.style.visibility='visible';
	});
	var myAjax = new Ajax.Request('/scripts/get-posts.py',{
		method: 'post',
		postBody: "page="+encodeURIComponent(curPage)+'&channel='+encodeURIComponent(channel),
		onComplete: function(response){
			var objects = response.responseText.evalJSON();
			paintUued(objects);
		}
	});
}

initTracker = function(){
	$$('a[class~=postlink]').each(function(t){
		t.observe('mousedown',function(){
			post_id = t.id.split('_')[1];
			var y = new Image;
			s=1;
			try{
				s= t.hasClassName('post-postlink')?0:1;
			}catch(E){}
			var channel = 0;
			try{
				channel = parseInt($('tagasi').down('img').id.split('_')[1]);
			}catch(E){}
			y.src = '/scripts/tracker.py?p='+post_id+'&s='+s+'&c='+channel;
		});
	});
	$$('a[class~=adlink]').each(function(t){
		t.observe('mousedown',function(){
			ad_id = t.id;
			var y = new Image;		
			y.src = ad_id;
		});
	});
}

handlePostsPreview = function(){

	initTracker();

	$$('span[class~=tagasi]').each(function(t){
		
		var channel = 0;
		try{
			channel = parseInt(t.down('img').id.split('_')[1]);
		}catch(E){}
		
		t.observe('click', function(){uuedTagasi(channel)});
	});
	$$('span[class~=edasi]').each(function(t){
		var channel = 0;
		try{
			channel = parseInt(t.down('img').id.split('_')[1]);
		}catch(E){}
		t.observe('click', function(){uuedEdasi(channel)});
	});
	$$('span[class~=refresh]').each(function(t){
		var channel = 0;
		try{
			channel = parseInt(t.down('img').id.split('_')[1]);
		}catch(E){}
		t.observe('click', function(){refreshUued(channel)});
	});


	$('numbers-not-enough').select('li').each(function(s){
		_loc_timer = false;
		function showPreview(){
			clearPreview();
			$('preview').down('div').update(s.down('[class~=p]').innerHTML);
			$('preview').style.left = s.cumulativeOffset().left+s.getWidth()+'px';
			$('preview').style.top = s.cumulativeOffset().top+'px';
			$('preview').show();
			s.addClassName('hover');
		}
		
		function hidePreview(){
			_loc_timer = window.setTimeout(clearPreview,10);
		}
		
		function clearPreview(){
			window.clearTimeout(_loc_timer);
			$('preview').hide();
			$$('li[class~=hover]').each(function(y){
				y.removeClassName('hover');
			});
		}
		
		s.observe('mouseover', showPreview);
		$('preview').observe('mouseover', function(){window.clearTimeout(_loc_timer)});
		s.observe('mouseout', hidePreview);
		$('preview').observe('mouseout', hidePreview);
	});

}

function closePromo(){
	$('adentro').remove();
	$('promobox').hide();
}

function showPromo(){
	var t = new Element('div',{id: 'adentro'}).setStyle({
		opacity: 0.5,
		height: getPageSize()[1]+'px',
		width: document.viewport.getWidth()+'px',
		position: 'absolute',
		left: 0,
		top:0,
		background: '#666'
	});
	t.observe('click',closePromo);
	document.body.appendChild(t);
	$('promobox').show();
	$('promocode').hide();
	$('promowait').hide();
	$('promoerror').hide();
	$('promobox').style.left = Math.round(document.viewport.getWidth()/2-$('promobox').getWidth()/2)+'px';
	$('promobox').style.top = document.viewport.getScrollOffsets().top+Math.round(getWSize().height/2-$('promobox').getHeight()/2)+'px'; 
	try{
		$('promobox').down('input[type=text]').value="";
		$('promobox').down('input[type=text]').focus();
	}catch(E){};
}

function checkPromo(){
	url = $('promobox').down('input[type=text]').value;
	$('promowait').show();
	$('promocode').hide();
	$('promoerror').hide();
	var myAjax = new Ajax.Request('/scripts/check-promo.py',{
		method: 'post',
		postBody: "url="+encodeURIComponent(url),
		onComplete: function(response){
			var e = trim(response.responseText);
			if(parseInt(e)){
				$('promo-id').innerHTML = e;
				$('promocode').show();
			}else
				$('promoerror').show();
			$('promowait').hide();
		}
	});
}

function getWSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return {width: myWidth, height: myHeight}
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
