function setupcarousel(){
  if (document.getElementById("horizontal_carousel")){
    var original_carousel = $$('#horizontal_carousel ul')[0].innerHTML;
    var count=(100/($$('#horizontal_carousel ul li').length)).ceil();
    $R(1,count).each(function(value){
      $$("#horizontal_carousel ul")[0].insert({bottom:original_carousel});
    });
    $('horizontal_carousel').addClassName('horizontal_carousel');
    var prevnext = '<ul class="prevnext"><li class="previous_button"></li><li class="next_button"></li></ul>';
    $("horizontal_carousel").insert({top:prevnext});
    var carousel = new UI.Carousel($("horizontal_carousel"));
    var carousel_imgs=$$('#horizontal_carousel .container li:not(#horizontal_carousel .container li:last) img');
    carousel_imgs.each(function(img){
      img.setStyle({'cursor':'pointer'})
      img.observe('click', function(event){
        carousel.scrollTo(carousel.currentIndex()+1);
      })
    });
  }
}

function external_links(){
	$('container').select('a[href$=.pdf]', 'a[href^=http://]:not(a[href*=itsnicethat.com])').each(function(link){
			link.writeAttribute({target:"_blank", title:"Javascript will open this external link in a new window."})
	});
}

function randomise_promo(){
	var promo = $('promo');
	if(promo) {
		var rnd = Math.floor(Math.random()*json_promos.length);
		promo.insert({bottom:'<h2>'+json_promos[rnd][0]+'</h2>'});
		promo.insert({bottom:'<a href="'+json_promos[rnd][2]+'"><img src="'+json_promos[rnd][1]+'"/></a>'});
		promo.insert({bottom:'<div id="promo_body">'+json_promos[rnd][3]+'</div>'});
	}
}

function jobs_description_truncate(){
  $$('li.job').each(function(list_item){
    list_item.select('.description', '.contact_website','.contact_email').each(function(el){ el.toggle();});
    list_item.select('.description_headline p:last')[0].insert({bottom:' <a>Read full job description</a>'});
    list_item.select('.description_headline a')[0].observe('click', function(event){
    	if (Event.element(event).innerHTML == 'Read full job description'){
    		//Event.element(event).innerHTML = 'Hide full job description';
    		Event.element(event).up('li').nextSiblings('li').each(function(el){ el.toggle();});
				Event.element(event).remove();
      //} else {
      //	Event.element(event).innerHTML = 'Read full job description';
    	//	Event.element(event).up('li').nextSiblings('li').each(function(el){ el.toggle();});
    	}
    });
  });
}

function setjobcounter() {
	var count = $('job_description').value.split(' ').length-1
	if (count >= 250) {
		$('description_counter').addClassName('feedback')
		$('description_counter').innerHTML = count+' words: Please note the 250 word limit, this may prevent your job being posted.'
	} else {
		$('description_counter').removeClassName('feedback')
		$('description_counter').innerHTML = count+' words'
	}
}

function jobdescriptioncounter() {
	//add the empty counter
	if ($('job_description') != null) {
		$('job_description').previousSiblings('label')[0].insert({bottom:"<span id='description_counter' class='counter'>counter</span>"});
		setjobcounter();
		$('job_description').observe('keyup',function(event) {
			setjobcounter();
		});
	}
}

function twitteriseComment() {
	
}

var shortUrl = '';
function getShortURL() {
	if (shortUrl == '') {
		var url = window.location.href;
		if (!url.include('http://www')) {
			url = url.gsub('http://','http://www.')
		}
		if (url.include('?')) {
			url = url.gsub(/\?.*/,'')
		}
		new Ajax.Request("/short_url?page="+url, {
		  method: 'get',
		  onSuccess: function(transport) {
				shortUrl = transport.responseText;
				$('comment_comment_on_twitter').value = '@itsnicethat '+$('comment_body').value.truncate(140-(shortUrl.length+14),'...')+' '+shortUrl;
			}
		});
	} else {
		$('comment_comment_on_twitter').value = '@itsnicethat '+$('comment_body').value.truncate(140-(shortUrl.length+14),'...')+' '+shortUrl;
	}
}

function setTwitterText() {
	if ($('comment_comment_on_twitter').up('p').style.display != 'none') {
		if ($('comment_body').value.length != 0) {
			getShortURL();
		}
	}
}

function setupCommentForm() {
	if ($('comments') && $('comment_post_on_twitter')) {

		if ($('comment_post_on_twitter').checked != true) {
			$('comment_comment_on_twitter').up('p').hide();
		}

		$('comment_post_on_twitter').observe('click', function(event){
			$('comment_comment_on_twitter').up('p').toggle();
			setTwitterText();
		});
	
		$('comment_body').observe('keyup', function(event){
			setTwitterText();
		});
	}
}

function setupComments(){
	if ($('comments')) {
		$('comments').select('li.comment').each(function(c) {
			toggleComment(c);
		});
	}
}

function toggleComment(comment){
	var body = $(comment.id).down('.comment_body');
	var paragraphs = body.select('p')
	
	if (body.select('.truncated').length != 0) {
		body.down('p.truncated').remove();
		body.insert("<a class='contract'>Hide full comment</a>")
		body.down('a.contract').observe('click', function(event){
			toggleComment(Event.element(event).up('li'));
		});
		paragraphs.each( function(p) {
			p.toggle();
		});

	} else {
		
		if (body.down('a.contract')) {
			body.down('a.contract').remove();
		}
		var char_cutoff = 255
		var text = ''
		paragraphs.each(function(p) {
			text = text+p.innerHTML;
		});
		if ( ((text.length > char_cutoff &&  !(text.length < char_cutoff+20)) || text.include('<br>' || text.include('</p>'))) && !comment.hasClassName('create_comment')) {
			text = text.gsub(/<\/p><p>|<br>/,' ')
			paragraphs.each( function(p) {
				p.toggle();
			});
			var words = text.substring(0,char_cutoff).split(' ');
			body.insert("<p class='truncated'>"+words.join(' ')+"... <a class='expand'>Show full comment</a></p>")
			body.down('.truncated').down('a.expand').observe('click', function(event){
				toggleComment(Event.element(event).up('li'));
			});
		}
	}
	
}

function twitterLoginJump(){
	if (window.location.href.include('oauth_token')) {
		window.location.href='#create_comment';
	}
}

document.observe("dom:loaded", function() {
	setupCommentForm();
	setupcarousel();
	external_links();
	randomise_promo();
	jobs_description_truncate();
	jobdescriptioncounter();
	setupComments();
	twitterLoginJump();
});
