// menu

function hoverMenuItem(itemName, show)
{	
	leftName 	= itemName+"Left";
	rightName 	= itemName+"Right";
	
	iL = document.getElementById(leftName);
	iR = document.getElementById(rightName);
	it = document.getElementById(itemName);
	
	if (show == "off")
	{
		iL.className = "menuItemLeft";
		iR.className = "menuItemRight";
		it.className = "menuItem";
	}
	else
	{
		iL.className = "menuItemLeftSelected";
		iR.className = "menuItemRightSelected";
		it.className = "menuItemSelected";
	}
}

function activateMenuItem(itemName)
{
	hoverMenuItem(itemName, "on");
	linkName = itemName+"Link";
	theLink = document.getElementById(linkName);
	theLink.onmouseover = "";
	theLink.onmouseout = "";
}

// apps

appsMenu = new Array("twitter", "vimeo", "flickr");
appsMenuNames = new Array("Twitter", "Vimeo", "Flickr");
actualApp = "";

function appClick(num)
{
	actualImgName = "app_img_active";
	appImgName = "app_img"+num;
	appLinkName	= "app_link"+num;
	actualAppName = "app_"+appsMenu[0];
	appName = "app_"+appsMenu[num];
	oldApp = appsMenu[0];
	oldName = appsMenuNames[0];
	
	actualImg = document.getElementById(actualImgName);
	appImg = document.getElementById(appImgName);
	appLink = document.getElementById(appLinkName);
	actualApp = document.getElementById(actualAppName);
	app = document.getElementById(appName);
	
	actualImg.src = "/wp-content/themes/imagemcia/images/app_"+appsMenu[num]+"_active.png";
	appImg.src = "/wp-content/themes/imagemcia/images/app_"+oldApp+".png";
	appImg.alt = oldName;
	appLink.title = oldName;
	
	actualApp.style.display = "none";
	app.style.display = "block";
	
	appsMenu[0] = appsMenu[num];
	appsMenu[num] = oldApp;
	
	appsMenuNames[0] = appsMenuNames[num];
	appsMenuNames[num] = oldName;
	
	switch(appsMenu[0])
	{
		case "twitter":
			getTwitter();
			break;
		case "vimeo":
			getVimeo();
			break;
	}
	
	actualApp = appsMenu[0];
}

function showImg(obj)
{
	document.getElementById(obj).style.display = "inline";
}

function hideImg(obj)
{
	document.getElementById(obj).style.display = "none";
}

// map

function initializeMap() {
	latlng = new google.maps.LatLng(-23.582824, -46.647531);
	myOptions = {
		disableDefaultUI: true,
		mapTypeControl: true,
	    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	    navigationControl: true,
	    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		zoom: 15,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("addressMap"), myOptions);
	
	marker = new google.maps.Marker({
		position: latlng, 
		map: map,
		title:"",
		icon: "/wp-content/themes/imagemcia/images/addressmarker.png"
	});
	
	google.maps.event.addListener(marker, 'click', function() {
		map.setZoom(19);
		map.setCenter(latlng);
	});
	
	google.maps.event.addListener(marker, 'dblclick', function() {
		window.open("http://maps.google.com.br/maps?f=q&source=s_q&hl=pt-BR&q=R.+Pelotas,+512+-+Vila+Mariana,+S%C3%A3o+Paulo,+04012-002&sll=-14.179186,-50.449219&sspn=76.910131,158.027344&ie=UTF8&cd=7&geocode=FZUnmP4dFDc4_Q&split=0&hq=&hnear=R.+Pelotas,+512+-+Vila+Mariana,+S%C3%A3o+Paulo,+04012-002&ll=-23.582807,-46.647532&spn=0.000599,0.001206&t=h&z=20","mapWindow","");
	});
	
	initLst = google.maps.event.addListener(map, 'tilesloaded', function() {
		mapLoaded = true;
		document.getElementById("addressMap").style.display = "none";
		document.getElementById("addressMap").style.marginTop = "42px";
		clearLst();
	});
	
	function clearLst()
	{
		google.maps.event.removeListener(initLst);
	}
}

function toggleMap()
{
	if (!mapLoaded) return;
	
	if (document.getElementById("addressMap").style.display == "none")
	{
		document.getElementById("addressMap").style.display = "block";
		document.getElementById("addressMapToggleLink").title = "Clique para fechar o mapa";
		document.getElementById("addressMapImgLink").title = "Clique para fechar o mapa";
		map.setZoom(15);
		map.setCenter(latlng);
	}
	else
	{
		document.getElementById("addressMap").style.display = "none";
		document.getElementById("addressMapToggleLink").title = "Clique para ver o mapa";
		document.getElementById("addressMapImgLink").title = "Clique para ver o mapa";
	}
}

// app realtime check
function realTimeCheckApp()
{
	if (actualApp == "") return;
	
	if (actualApp == "twitter")
	{
		getTwitter();
	}
	else if (actualApp == "vimeo")
	{
		getVimeo();
	}
	
	setTimeout("realTimeCheckApp()", 600000);
}

// twitter

function getTwitter()
{
	window.getTwitters('twitterAppContent', {
		id: 'imagemcia', 
		count: 20, 
		enableLinks: true,
		clearContents: true,
		template: '<div class="tweet">%text%<br /><a class="twitterTime" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a></div><div class="tweetSeparator"><hr /></div>'
	});
}

// vimeo

function getVimeo()
{	
	var vimeoUserName = 'imagemcia';
	var callback = 'showVimeo';
	var url = 'http://www.vimeo.com/api/v2/' + vimeoUserName + '/videos.json?callback=' + callback+"&rand="+Math.random();
	
	var js = document.createElement('script');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', url);
	document.getElementsByTagName('head').item(0).appendChild(js);
}

function showVimeo(videos)
{
	var thumbs = document.getElementById('vimeoAppContent');
	thumbs.innerHTML = '';
	
	var html = '';
	
	for (var i = 0; i < videos.length; i++) {
		html += '<div class="vimeoItem">';
		html += '	<a href="'+videos[i].url+'" title="'+videos[i].title+'" class="vimeoLink"><img src="'+videos[i].thumbnail_small+'" alt="'+videos[i].title+'" class="vimeoThumb" /></a>';
		html += '	<div class="vimeoText">';
		html += '		<a href="'+videos[i].url+'" title="'+videos[i].title+'" class="vimeoLink">'+videos[i].title+'</a><br />';
		html += '		'+format_relative_time(videos[i].upload_date);
		html += '	</div>';
		html += '</div>';
		html += '<div class="vimeoSeparator"><hr /></div>';		
	}
	
	thumbs.innerHTML = html;
}

// format date
var format_monthDict = ['Janeiro', 'Fevereiro', 'Mar&ccedil;o', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];

function format_relative_time(time_value) {	
	var sepValues = time_value.split(" ");
	var dateValues = sepValues[0].split("-");
	
    var parsed_date = Date.parse(dateValues[1] + "/" + dateValues[2] + "/" + dateValues[0] + " " + sepValues[1]);
    var date = new Date(parsed_date);
    
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    var r = '';
    
    function formatTime(date) {
        var hour = date.getHours();
        var min = date.getMinutes() + "";
        //var ampm = 'AM';
        
        /*
        if (hour == 0) {
            hour = 12;
        } else if (hour == 12) {
            ampm = 'PM';
        } else if (hour > 12) {
            hour -= 12;
            ampm = 'PM';
        }
        */
        
        if (min.length == 1) {
            min = '0' + min;
        }
        
       // alert(hour);
       // alert(min);
        
        return hour + ':' + min;
    }
    
    function formatDate(date) {
        var ds = date.toDateString().split(/ /);
        var mon = format_monthDict[date.getMonth()];
        var day = date.getDate()+'';
        var dayi = parseInt(day);
        var year = date.getFullYear();
        var thisyear = (new Date()).getFullYear();
        var th = '';
        
        // anti-'th' - but don't do the 11th, 12th or 13th
        if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
            th = '';
        } else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
            th = '';
        } else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
            th = '';
        }
        
        if (day.substr(0, 1) == '0') {
            day = day.substr(1);
        }
        
        //alert(day);
        //alert(mon);
        //alert(year);
        
        return day + th  + ' de ' + mon + (thisyear != year ? ' de ' + year : '');
    }
    
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 5) {
        r = 'há menos de 5 segundos';
    } else if (delta < 30) {
        r = 'há meio minuto';
    } else if (delta < 60) {
        r = 'há menos de um minuto';
    } else if (delta < 120) {
        r = 'há 1 minuto';
    } else if (delta < (45*60)) {
        r = 'há ' + (parseInt(delta / 60)).toString() + ' minutos';
    } else if (delta < (2*90*60)) { // 2* because sometimes read 1 hours ago
        r = 'há cerca de 1 hora';
    } else if (delta < (24*60*60)) {
        r = 'há cerca de ' + (parseInt(delta / 3600)).toString() + ' horas';
    } else {
        if (delta < (48*60*60)) {
            r = 'Ontem &agrave;s ' + formatTime(date);
        } else {
            r = formatDate(date) + ' &agrave;s ' + formatTime(date);
            // r = (parseInt(delta / 86400)).toString() + ' days ago';
        }
    }

    return r;
}

// test browser
var testbrowser = (function() {
    var b = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    return {
        webkit: /(webkit|khtml)/.test(b),
        opera: /opera/.test(b),
        msie: /msie/.test(b) && !(/opera/).test(b),
        mozilla: /mozilla/.test(b) && !(/(compatible|webkit)/).test(b)
    };
})();

// init

function initPage()
{
	mapLoaded = false;
	hideImg("twitter_footer_over");
	initializeMap();
	actualApp = "twitter";
	realTimeCheckApp();
}
