var WITTEL = window.WITTEL || {};
var startup = function(){
	WITTEL.navMain('#mainNav');
	$('a[rel*=external]').attr('target','_blank');
	if($('#clientGallery').length) {
		WITTEL.clientGallery();
	}
	if($('#carousel').length) {
		$.ajax({
			dataType:'xml',
			url:'xml/carousel.xml',
			success:function(data) {
				var child = (data.firstChild && data.firstChild.nodeName == 'xml')?1:0;
				var itens = data.childNodes[child].getElementsByTagName('item');
				if(!itens.length)return;
				var ul = $(document.createElement('ul')).attr('id','mycarousel').addClass('jcarousel-skin-wittel');
				for(var i=0;i<itens.length;i++) {
					var img = $(document.createElement('img')).attr('src',itens[i].getAttribute('src')).css('width',215);
					if(itens[i].getAttribute('href'))
						img = $(document.createElement('a')).attr('href',itens[i].getAttribute('href')).append(img);
					$(document.createElement('li')).append(img).appendTo(ul);
				}
				$('#carousel').append(ul);
				ul.jcarousel({
					wrap: 'circular',
					initCallback:function(c) {
						setInterval(function() {
							c.next();
						},10000);
					}
				});
			}
		});
	}
	if($('#destHome').length) {
		$.ajax({
			dataType:'xml',
			url:'xml/vitrine.xml',
			success:function(data) {
				var child = (data.firstChild && data.firstChild.nodeName == 'xml')?1:0;
				var itens = data.childNodes[child].getElementsByTagName('item');
				var list = [];
				for(var i=0;i<itens.length;i++) {
					list.push({
						href:itens[i].getAttribute('href'),
						img:itens[i].getAttribute('src'),
						title:itens[i].getElementsByTagName('title').length?itens[i].getElementsByTagName('title')[0].firstChild.data:'',
						content:itens[i].getElementsByTagName('content').length?itens[i].getElementsByTagName('content')[0].firstChild.data:'',
						mini:itens[i].getAttribute('mini'),
						tooltip:itens[i].getAttribute('title')
					});
				}
				i=0;
				var rdmList = {}, j;
				while(i < list.length) {
					j = Math.floor(Math.random() * list.length);
					if(!(j in rdmList)) {
						rdmList[j] = list[j];
						i++;
					}
				}
				list.length = 0;
				for(var prop in rdmList) {
					list.push(rdmList[prop]);
				}
				WITTEL.destHome = new vitrine({
					list:list,
					elm:'#destHome',
					html:'<a class="link" href="%href"></a><h2>%title</h2><p>%content</p>%listTo',
					timer:15000,
					
					doTimer:function(i) {
						for(var i=0;i<WITTEL.destHome.list.length;i++)
							$('#destHome .listTo li span').eq(i).html('<img src="' + WITTEL.destHome.list[i].mini + '" />');
						
					}
				});
				for(var i=0;i<WITTEL.destHome.list.length;i++)
					$('#destHome .listTo li span').eq(i).html('<img src="' + WITTEL.destHome.list[i].mini + '" />');
			}
		});
	}
	if($('#twitter').length)
		WITTEL.getLastTweets();
	
	if($('#content .listNews').length)
		WITTEL.getLastNews();
};
$(startup);

WITTEL.getLastTweets = function() {
	var html = '';
	//$.getJSON('http://search.twitter.com/search.json?q=from%3Awittelbrasil&rpp=5&callback=?',
	$.getJSON('http://www.twitter.com/statuses/user_timeline/wittelbrasil.json?count=5&callback=?',
        function(data){
			$('#twitter').data('twits',data.results || data);
			$('#twitter').data('twit',-1);
			var troca = function() {
				var twits = $('#twitter').data('twits'),
					twit = $('#twitter').data('twit');
				if(!twits.length)
					return;
				$('#twitter #loader').replaceWith(document.createElement('p'));
				if(!twits[++twit])
					twit = 0;
				$('#twitter').data('twit',twit);
				
				$('#twitter p')
					.fadeOut('',function() {
						$(this).html(twits[twit].text.replace( /(http:\/\/[^ ]+)/, "<a href='$1' target='_blank'>$1</a>" )).fadeIn();
					});
				
			};
			troca();
			setInterval(troca,10000);
		}
	);
};
WITTEL.getLastNews = function() {
	$.getJSON('http://www.twitter.com/statuses/user_timeline/wittelbrasil.json?count=20&callback=?',
		function(data) {
			data = data.results || data;
			var frag = document.createDocumentFragment();
			for(var i=0,len=data.length;i<len;i++) {
				var p = document.createElement('p');
				p.innerHTML =data[i].text.replace( /(http:\/\/[^ ]+)/, "<a href='$1' target='_blank'>$1</a>" );
				frag.appendChild(p);
			}
			$('#content .listNews')[0].appendChild(frag);
		}
	);
}
WITTEL.toogleText = function(id){
	var dt = $(id + ' dt');
	
	$(id + ' dd').hide();
	
	for(var i=0;i<dt.length;i++) {
		if(dt.eq(i).next()[0].tagName.toLowerCase() == 'dd') {
			dt.eq(i).append('<span>(+)</span>');
		}
		
	}
	dt.click(function() {
			var $this = $(this);
			if($this.next()[0].tagName.toLowerCase() == 'dd') {
				if($this.next().css('display') == 'none') { //Aqui abre
					$this.find('span').text('(-)');
					$this.next().show();
				}
				else { //Aqui fecha
					$this.find('span').text('(+)');
					$this.next().hide();
				}
			}
			
		});
}
WITTEL.navMain = function(){
	$('#sobre').mouseover(function() {
		$('#subSobre').show();
	});
	$('#solucoes').mouseover(function() {
		$('#subSol').show();
	});
	$('#servTrein').mouseover(function() {
		$('#subServ').show();
	});
	
	$('#sobre').mouseout(function() {
		$('#subSobre').hide();
	});
	$('#solucoes').mouseout(function() {
		$('#subSol').hide();
	});
	$('#servTrein').mouseout(function() {
		$('#subServ').hide();
	});
}
var mycarousel_itemList = [
        {url: '../img/img-cliente1.gif', title: 'Santander'},
        {url: '../img/img-cliente2.gif', title: 'Ipiranga'},
        {url: '../img/img-cliente3.gif', title: 'Tivit'},
        {url: '../img/img-cliente4.gif', title: 'Bradesco'},
        {url: '../img/img-cliente5.gif', title: 'Pernambucanas'},
        {url: '../img/img-cliente6.gif', title: 'Citibank'},
        {url: '../img/img-cliente7.gif', title: 'TIM'},
        {url: '../img/img-cliente8.gif', title: 'Embratel'},
        {url: '../img/img-cliente9.gif', title: 'Contax'},
        {url: '../img/img-cliente10.gif', title: 'Atento'},
        {url: '../img/img-cliente11.gif', title: 'Algar'},
        {url: '../img/img-cliente12.gif', title: 'Gol'},
        {url: '../img/img-cliente13.gif', title: 'Tam'},
        {url: '../img/img-cliente14.gif', title: 'Arcelor Mittal'},
        {url: '../img/img-cliente15.gif', title: 'Votorantim'},
        {url: '../img/img-cliente16.gif', title: 'Banco Central'},
        {url: '../img/img-cliente17.gif', title: 'Braskem'},
        {url: '../img/img-cliente18.gif', title: 'Itau'},
        {url: '../img/img-cliente19.gif', title: 'Banco do Brasil'},
        {url: '../img/img-cliente20.gif', title: 'American Express'},
    {url: '../img/img-cliente21.gif', title: 'Cielo'}
];
WITTEL.clientGallery = function(){
	shuffle(mycarousel_itemList);
	$('#clientGallery').jcarousel({
		auto: 7,
		animation: 1000,
		wrap: 'circular',
		vertical: true,
		itemVisibleInCallback: {onBeforeAnimation: mycarousel_itemVisibleInCallback},
		itemVisibleOutCallback: {onAfterAnimation: mycarousel_itemVisibleOutCallback},
		initCallback: mycarousel_initCallback
	});
}
shuffle = function(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};
function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};
function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt)
{
    // The index() method calculates the index from a
    // given index who is out of the actual item range.
    var idx = carousel.index(i, mycarousel_itemList.length);
    carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[idx - 1]));
};

function mycarousel_itemVisibleOutCallback(carousel, item, i, state, evt)
{
    carousel.remove(i);
};
function mycarousel_getItemHTML(item)
{
    return '<img src="' + item.url + '" width="176" height="65" alt="' + item.title + '" />';
};
