var apiHost = 'http://api.community.virgilio.it';
var genio_box;
var genio_numItem = 5;

function isValid(parameterToCheck) {
	return (parameterToCheck != null && parameterToCheck != '');
}
function padNum(len, num){
    return Array(len + 1 - ('' + num).length).join("0") + num;
}

function tabsManager() {
	$("#tabs a").click(function(){ 
		$("#tabs a").removeClass("tab_on").addClass("tab"); 
		$(this).removeClass("tab").addClass("tab_on"); 
		var currentTab = $(this).attr("href"); // Set variable currentTab to value of href attribute of clicked link
		$("#panels .tab_box_1").hide();
		$("#panels .tab_box_2").hide();
		$("#panels .tab_box_3").hide();
		$(currentTab).fadeIn(400); 
		return false;
	});
}

function checkWebIdOnSubmit() {
	var reContainsWhiteSpace = new RegExp(/\s+/);
	var webId = $("#webIdParam").attr("value");
	if (webId == "inserisci il tuo dominio") {
		$("#webIdParam").attr("value", "");
	} else if (reContainsWhiteSpace.test(webId)) { // Check for white space
        alert("Per favore, controlla che non ci siano spazi nel tuo WebId");
        $("#webIdParam").attr("value", webId.replace(/\s/g, ""));
        return false;
    }	
	return true;
}

function api_community_xoom_dashBoardInfo(data){		
	try {			
		var dashBoardInfos = data;
					
		if (  dashBoardInfos != null ) {

			if ( isValid(dashBoardInfos.apiXoomDashboard.pageViewToday) ) {
				$("#pageViewToday").empty().append(dashBoardInfos.apiXoomDashboard.pageViewToday);
			}
			if ( isValid(dashBoardInfos.apiXoomDashboard.pageViewWeek) ) {
				$("#pageViewWeek").empty().append(dashBoardInfos.apiXoomDashboard.pageViewWeek);
			}
			if ( isValid(dashBoardInfos.apiXoomDashboard.pageViewMonth) ) {
				$("#pageViewMonth").empty().append(dashBoardInfos.apiXoomDashboard.pageViewMonth);
			}
			if ( isValid(dashBoardInfos.apiXoomDashboard.uniqueViewToday) ) {
				$("#uniqueViewToday").empty().append(dashBoardInfos.apiXoomDashboard.uniqueViewToday);
			}
			if ( isValid(dashBoardInfos.apiXoomDashboard.uniqueViewWeek) ) {
				$("#uniqueViewWeek").empty().append(dashBoardInfos.apiXoomDashboard.uniqueViewWeek);
			}
			if ( isValid(dashBoardInfos.apiXoomDashboard.uniqueViewMonth) ) {
				$("#uniqueViewMonth").empty().append(dashBoardInfos.apiXoomDashboard.uniqueViewMonth);
			}
			var today = new Date();
	        var year = today.getFullYear();
	        var month = today.getMonth();
	        var date = today.getDate();
	        var stringDate = "<span>" + padNum(2, date) + "</span>" + "/" + padNum(2,month + 1) + "/" + new String(year).substring(2);
	        $("#dashBoardDate").empty().html(stringDate);
			
		}
	}
	catch (err) {
		if (window.console) {
			window.console.log(err);
		}
	}	

}

function scrollCreaSito() {
	$("#hp_tab a.crea").click(function (event) {
		$("#contenuto").animate({ marginLeft: "0px"}, 500 );
		$(".tab_on").removeClass("tab_on").addClass("tab");
		$(this).parent().removeClass("tab").addClass("tab_on");
		event.preventDefault();
	});
	
	$("#hp_tab a.wizard").click(function (event) {
		$("#contenuto").animate({ marginLeft: "-630px"}, 500 );
		$(".tab_on").removeClass("tab_on").addClass("tab");
		$(this).parent().removeClass("tab").addClass("tab_on");
		event.preventDefault();
	});
	
	$("#hp_tab a.avanzato").click(function (event) {
		$("#contenuto").animate({ marginLeft: "-1260px"}, 500 );
		$(".tab_on").removeClass("tab_on").addClass("tab");
		$(this).parent().removeClass("tab").addClass("tab_on");
		event.preventDefault();
	});
	
	$("#hp_tab a.premi").click(function (event) {
		$("#contenuto").animate({ marginLeft: "-1890px"}, 500 );
		$(".tab_on").removeClass("tab_on").addClass("tab");
		$(this).parent().removeClass("tab").addClass("tab_on");
		event.preventDefault();
	});
}

function api_community_sitipersonalinews_editorial(data){
	
	setTimeout("displayLastSiteNews()", 50);
	
	displayLastSiteNews = function(){
		try {
			var lastSiteNews = data.box.items;
			if (  lastSiteNews != null ) {
				for (var i = 0; i < lastSiteNews.length && i < 10; i++) {
					var lastNew = lastSiteNews[i];
					var mostra = false;
					
					if ( isValid(lastNew.url2) ) {
						$("#notiziaUrl_" + i).empty().append(lastNew.url2).attr("href", lastNew.url2);
						mostra = true;
					}
					if ( isValid(lastNew.titleText) ) {
						$("#notiziaBody_" + i).empty().append(lastNew.titleText);
						mostra = true;
					}
					if ( isValid(lastNew.lastupdatetime) ) {
						$("#notiziaData_" + i).empty().append(lastNew.lastupdatetime);
						mostra = true;
					}
					
					if (mostra)
						$("#notizia_" + i).removeClass("hidden");				
					
				}
			}
		}
		catch (err) {
			if (window.console) {
				window.console.log(err);
			}
		}
		
	}	
}

function api_community_genio_ultimedomande(data) {
	genio_box = data.box;
	setTimeout("displayGenio()", 10);

	displayGenio = function() {

		try {
			for ( var n = 0; n < genio_numItem; n++) {
				var itm = genio_box.items[n];
				var idQuestion = "genioQuestion" + n;
				var iduser = "genioUser" + n;
				var $titolo = $("#" + idQuestion + " > a.principale");

				if (isValid(itm.titleText)) {
					$titolo.empty().append(itm.titleText);
					if (isValid(itm.titleLink)) {
						$titolo.attr("href", itm.titleLink);
					}
				} else {
					$titolo.css("visibility", "hidden");
				}
				var $AnchorNode = $("#" + idQuestion + " > a:eq(0)");
				var $imgNode =$AnchorNode.children("img");
				if (itm.user != null && itm.user.avatarImageLink != null
						&& itm.user.avatarImageLink != '') {

					$imgNode.attr("src", itm.user.avatarImageLink);
					$imgNode.css("display", "block").css(
							"visibility", "visible");
					if (itm.user.nicklink != null && itm.user.nicklink != '') {
						$AnchorNode.attr("href", itm.user.nicklink);
					}
				} else {
					$AnchorNode.css("visibility", "hidden");
				}
				var $userNode = $("#" + iduser);
				var $anchorUserNode = $userNode.children("a");
				if (itm.user != null && itm.user.nickname != null
						&& itm.user.nickname != '') {
					$anchorUserNode.empty().append(itm.user.nickname);
					$userNode.css("display", "block");
					if (itm.user.nicklink != null && itm.user.nicklink != '') {
						$anchorUserNode.attr("href", itm.user.nicklink);
					}
				} else {
					$userNode.css("visibility", "hidden");
				}
			}
			setTimeout("load_Genio()", 60000);
		} catch (errGenio) {
			if (window.console) {
				window.console.log(errGenio);
			}
		}
	}
}

function loadLastSiteNews(){
	$.getScript(apiHost + "/static/editorial/sitipersonali/last_site_news.js");
}
function load_Genio() {
	$.getScript(apiHost + "/static/genio/ultimedomande-xoom.js");
}

function presence(){
	$('div.nickname').c6Presence({
		'selector': 'div.nickname'
    });
}
var presenceTimeout;
function presenceTimer(timer){
	clearTimeout(presenceTimeout);
    presenceTimeout = setTimeout(presence, timer);	
}
var intervalID;
function presenceInterval() {
 intervalID = setInterval(presence, 120000);
}

function loadAdv() {
	create_iframe($("#banner_adv"), "adv7","/xoom/adv/ifr_virg_comu_home_cachebust.js_300x250.html?advTile=" + bust, 250, 300);
}

function create_iframe(parent, id, src, height, width){
	if ((parent != undefined) && (parent.get(0) != undefined)) {
		if (document.getElementById(id) == undefined) {
			iframe = createIframe(parent.get(0));
			iframe.id = id;
			iframe.src = src;
			iframe.height = height;
			iframe.width = width;
			iframe.style.display ="block";
			iframe.marginheight="0" ;
			iframe.hspace="0" ;
			iframe.vspace="0" ;
			iframe.frameBorder="0" ;
			iframe.scrolling="no" ;
			iframe.style.border=0 ;
			iframe.bordercolor="#000000";
			
		}	
	}
	function createIframe(parentElement)
	{
		// Create the iframe which will be returned
		var iframe = null;
		try {if (iframe == null) iframe = document.createElement("<iframe scrolling=\"no\" frameborder=\"0\"/>");} catch (e) {}
		try {if (iframe == null) iframe = document.createElement("iframe");} catch (e) {}
		iframe.scrolling="no";
		iframe.style.frameborder=0;
		iframe.style.display = "none";
		// If no parent element is specified then use body as the parent element
		if(parentElement == null)
			parentElement = document.body;

		// This is necessary in order to initialize the document inside the iframe
		parentElement.appendChild(iframe);

		// Initiate the iframe's document to null
		iframe.doc = null;

		// Depending on browser platform get the iframe's document, this is only
		// available if the iframe has already been appended to an element which
		// has been added to the document
		if(iframe.contentDocument){
		// Firefox, Opera
			iframe.doc = iframe.contentDocument;
			// 	Create the script inside the iframe's document which will call the
		}
		else if(iframe.contentWindow)
			// Internet Explorer
			iframe.doc = iframe.contentWindow.document;
		else if(iframe.document){
			// Others?
			iframe.doc = iframe.document;
			// Create the script inside the iframe's document which will call the
		}
		// If we did not succeed in finding the document then throw an exception
		if(iframe.doc == null)
			throw "Document not found, append the parent element to the DOM before creating the IFrame";

		

		// Return the iframe, now with an extra property iframe.doc containing the
		// iframe's document
		return iframe;
	}

}



$(document).ready(function(){
	
	$.ajaxSetup({cache:true});
	scrollCreaSito();	
	tabsManager();
	setTimeout("loadAdv()", 1100);
	setTimeout("loadLastSiteNews()", 150);
	setTimeout("load_Genio()", 150);
	presenceTimer(1000);
	presenceInterval();
	
	$('div.nick_dx').addFriendDialog({
		addSelector: "a.nick_agg", 
		nickSelector: "span.nick > a",
		urlDialog: "/xoom/dialog/addFriend.html div.friendAlert",
		loginPageType: "xoom"
	});
	      
});
