// JavaScript Document
function filter_practice(s){
  if (s.options[s.selectedIndex].className == "opt-group") {
     s.options[0].selected = true;
     return;
  }
	var theform = document.getElementById("practiceform");
	var val_row = s.options[s.selectedIndex].value;
  if(val_row == "-") {
		return;
	}
	theform.action = val_row;
	theform.submit();
}
function checkProfessione(s,reset) {
	$(".professioni").css("display","none");
	var prof = $(".professioni");
	if(!reset){
		prof.find("input").val("");
	}
	if ($("#professione"+s.value).length > 0) {
	 $("#professione"+s.value).fadeIn("slow");
	 //footer();
	}
}
function clickTab(n) {
	var targetedtab =  $("ul.tabs a:eq("+(n-1)+")");
	targetedtab.click();
}
function tabs() {
	var tabs =  $("ul.tabs a");
	if (tabs.length <= 0) return;
	
	var isdoubleopener = tabs.parent().parent().hasClass("doubleopener");
	if (isdoubleopener == false) {
		var c = tabs.filter(".current").get(0).href;
		var currentdiv = $(c.substring(c.lastIndexOf("#")));
		currentdiv.show().siblings().hide();
	} else {
		//if is a double opener, none of the divs with id="tab_n" must be defaultly selected.
		tabs.removeClass("current");
		var c = null;
		var currentdiv = null;
		for(var i = 0; i < tabs.length; i++) {
			c = tabs.get(i).href
			currentdiv =  $(c.substring(c.lastIndexOf("#")));
			currentdiv.hide();			
		}
		
	}
	tabs.click(function() {
		tabs.removeClass("current");
		$(this).addClass("current");
		var targetid = this.href.substring(this.href.lastIndexOf("#"));
		$(targetid).css("display","none").fadeIn("slow").siblings().css("display","none");
		
		//if is a double opener, divs with id="tab_n_another" must be also displayed.
		if (isdoubleopener == true) {
			$(".tab_another").css("display","none");
			$(targetid+"_another").fadeIn("slow");
		}
		
		//footer();
		return false;
	});
}
function footer() {
  //$("#footer").css("visibility","hidden");
	setInterval(function() {
  
  		var sheet = $("#sheet");
  		//alert(sheet.height() + " -" + sheet.outerHeight() + " - " + parseInt(sheet.css("top")));
  		
  		$("#footer").css({
  			"top" : 		(34 + sheet.outerHeight() + parseInt(sheet.css("top"))) + "px",
  			"visibility" : 	"visible"
  		});	
  	
	});
/*  var itt = setInterval(function() {
    var sheet = $("#sheet");
  	var content = $("#content-container");
  	var topto;
  	if (content.height()+74 < sheet.height()) {
  		topto = (sheet.height()+parseInt(sheet.css("top")))+"px";
  	} else {
  		topto = (content.height()+74+parseInt(sheet.css("top")))+"px";
  	}
  	$("#footer").css("top",topto);
  	$("#footer").css("visibility","visible");
	},1000);
*/
	//parify between content-left and content-right if content-right exists
  /*var cright = $(".content-right");
  if (cright) {
   cright.css("background","#ff0000");
   cright.height($(".content-left").height());
  }*/
  
}
function populateSchool() {
	var selects = $(".populateschool");
	if (selects.length <= 0) return;
	selects.change(function() {
		var selectedvalue = ($(this).val());
		if (selectedvalue == "-") return;
		var populateschooldata = $(".populateschooldata");
		
		populateschooldata.html("<img src='/images/loading.gif' />");
		//populateschooldata.load("/carriera/responses/schooldata.view",{school_id:selectedvalue},footer)
		populateschooldata.load("/carriera/responses/schooldata.view",{school_id:selectedvalue})
				
	} );
}
/*function checkWaterfallAndSubmit(formname) {
  var f = document.forms[formname];
  var selects = f.getElementsByTagName("select");
  var ws = new Array();
  var trattini = 0;
  for (var i = 0; i < selects.length; i++) {
    if(selects[i].className.indexOf ("waterfallselect") != -1 && selects[i].value == "-") {
      trattini++;    
    }
  }
  if (trattini < selects.length) {
    f.submit();
  }
}*/
function waterfallSelects() {
  var selects = $(".waterfallselect");
  if (selects.length <=0) return;
  selects.change(function() {
    var select0 = selects.eq(0);
    var select1 = selects.eq(1);
    var select2 = selects.eq(2);
    
    var idx = selects.index(this);
    if (idx == 0) {
        select1.html("");
        select1.css("background","url('/images/loading.gif') no-repeat 10px top");
        select2.html("");
			  select2.css("background","url('/images/loading.gif') no-repeat 10px top");
        select1.load("/idee/responses/selectnews0.view",{waterfallselect0:select0.val()},function() {
          select1.css("background","#f0f0f0");  
			    select2.load("/idee/responses/selectnews1.view",{waterfallselect0:select0.val(),waterfallselect1:select1.val()},function() {
			     select2.css("background","#f0f0f0");
		      } );
		    } ); 
    } else if (idx == 1) {
        //preventing selection of fake voices!
        if (select1.val() == "-") {
          select1.get(0).options[0].selected = true;  
        }
        select2.html("");
        select2.css("background","url('/images/loading.gif') no-repeat 10px top");
       	select2.load("/idee/responses/selectnews1.view",{waterfallselect0:select0.val(),waterfallselect1:select1.val()},function() {
			   select2.css("background","#f0f0f0");
		    } );
    }
  } );
}

function tinyImgSwf() {
	var swfs = new Array();
	var imgs = $(".mceItemFlash");
	if (imgs.length == 0) return;
	imgs.css("border","1px solid red");
	for (var count = 0; count < imgs.length; count++) {
		var el = imgs.get(count);
		swfs[count] = new Object();
		swfs[count].width = el.getAttribute("width");
		swfs[count].height = el.getAttribute("height");
		swfs[count].src = el.getAttribute("alt");
		$(el).replaceWith("<object width='"+swfs[count].width+"' height='"+swfs[count].height+"'><param name='movie' value='"+swfs[count].src+"'><embed src='"+swfs[count].src+"' width='"+swfs[count].width+"' height='"+swfs[count].height+"'></embed></object>");
	}
}
function rndNews() {
	var allnews = $(".rndnews");
	if(allnews.length == 0) return;
	allnews.css("display","none");
	var rnd1,rnd2;
	rnd1 = rnd2 = Math.floor(allnews.length*Math.random());
	if(allnews.length > 1) {
		while (rnd1 == rnd2) {
			rnd2 = Math.floor(allnews.length*Math.random());	
		}
	
		//eventually correct order.
		if(rnd1 > rnd2) {
			var temprnd = rnd2;
			rnd2 = rnd1;
			rnd1 = temprnd;
		}
	
		//display randomized two news and remove separator div for the 2nd one.
		$(".rndnews:eq("+rnd1+")").css("display","block");
	}
	$(".rndnews:eq("+rnd2+")").css("display","block").find(".separator").remove();
}
function rndProjects() {
  var allprojects = $(".rndprojects");
  if (allprojects.length == 0) return;
  allprojects.css("display","none");
  var rnd = Math.floor(allprojects.length*Math.random());
  //if(allprojects.length > 1) {
    $(".rndprojects:eq("+rnd+")").css("display","block");
  //}
}
function peopleTooltips() {
	var box = $(".tooltipbox");
	var containerpos = $("#content-container").offset();
	$(".tooltip").mouseover(function(e) {
		var current = $(this);
		var currentpos = current.offset();
		var descr = current.get(0).getElementsByTagName("div")[0].innerHTML;
		box.css("left",currentpos.left-containerpos.left+30);
		box.css("top",currentpos.top-containerpos.top+70);
		box.html("<div class='descr'>"+descr+"</div>");
		box.css("display","block");
	});
	$(".tooltip").mouseout(function() {
		box.css("display","none");
	});
}
function filettos() {
  var filettodivs = $("div.content-right div.content-box div.entry");
  for(var i = 0; i < filettodivs.length; i++) {
    filettodivs.get(i).father = filettodivs.get(i).parentNode;
    while (filettodivs.get(i).father.className.substring(0,11) != "content-box") {
        filettodivs.get(i).father = filettodivs.get(i).father.parentNode;
    }
    if (i != 0 && filettodivs.get(i).father != filettodivs.get(i-1).father) {
      filettodivs.get(i-1).style.borderBottom = "none";
    } 
    if (i == filettodivs.length-1) {
      filettodivs.get(i).style.borderBottom = "none";
    }
  }
}
function ieSelectionBugFix(){
	 if (window.createPopup && document.compatMode && document.compatMode=="CSS1Compat")
	{
	  document.onreadystatechange = onresize = function fixIE6AbsPos()
	  {
	    if (!document.body) return;
	    if (document.body.style.margin != "0px") document.body.style.margin = 0;
	    onresize = null;
	    document.body.style.height = 0;
	    setTimeout(function(){ document.body.style.height = document.documentElement.scrollHeight+'px'; }, 1);
	    setTimeout(function(){ onresize = fixIE6AbsPos; }, 100);
	  }
	}	
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function wopen(url,wname,features) {
  if(!wname) wname = "w"+new Date().getTime();
  window.open(url,wname,features);
}


//favourites:
function blurFavourites(txtarea) {
  var editablediv = $(txtarea).parent();
  if (editablediv.get(0).committing != true) {
    if(editablediv.get(0).textContent) {
      editablediv.text(editablediv.get(0).txt);
    } else {
      editablediv.get(0).innerText = editablediv.get(0).txt;
    }
  }
  editablediv.get(0).committing = false;
}
function commitFavourites(btn) {
  var txtarea = $(btn).parent().children("textarea");
  var editablediv = txtarea.parent();
  var maindivdom = txtarea.parent().parent().parent().get(0);
  var commentid = maindivdom.getAttribute("tnes:id");
  
  editablediv.prepend("<img src=\"images/loadingfav.gif\" width=\"16\" height=\"16\"/><br />");
  txtarea.css("display","none");
  var editabledivdom = editablediv.get(0);
  editabledivdom.committing = true;
  var newtext = txtarea.val();
  //alert(">>>"+newtext)
  //alert("id del commento:"+commentid);
  //$.post("/idee/responses/favedit.view", {text:newtext },
  $.post("/idee/my_mckinsey/bookmark/bookmark-"+commentid+".save", {msg:newtext,bookmark_id:commentid,_tnes_redirect_ok:"/idee/responses/favedit.view?msg=" + encodeURI(newtext),_tnes_redirect_ko:"/idee/responses/favedit.view?msg=" + newtext},
    function(returnedtext){
      if (editabledivdom.textContent) {
        editablediv.text(returnedtext)
      } else {
        editabledivdom.innerText = returnedtext;
      }
  });
}
function initFavourites() {
   var favedits = $(".favedit");
   var favdeletes = $(".favdelete");
   favedits.click(function() {
        var editablediv = $(this).parent().prev(".favcontent").children(".editable");
        var editabletext = (editablediv.get(0).textContent ? editablediv.text() : editablediv.get(0).innerText)
        editablediv.txt = editablediv.get(0).txt = $.trim(editabletext);
        editablediv.html("<textarea onBlur=\"blurFavourites(this)\">"+editablediv.txt+"</textarea><br /><input type=\"button\" class=\"button-aggiorna\" value=\"\" onMouseDown=\"commitFavourites(this);\" />");
        editablediv.children("textarea").focus();
        return false;
   });
   favdeletes.click(function() {
        if (window.confirm("AVVISO\nStai per eliminare questa pagina dal tuo elenco di pagine preferite.\nSei sicuro di voler procedere?")) {
          $(this).css("background","url('/images/loadingfav.gif') no-repeat center center");
          var removediv = $(this).parent().parent();
          var removeid = removediv.get(0).getAttribute("tnes:id");
          
          //new code
          var section = removediv.attr("name");
          $.post("/idee/my_mckinsey/bookmark/bookmark-"+removeid+".trash", {_tnes_redirect_ok:"/idee/responses/favdelete.view",_tnes_redirect_ko:"/idee/responses/favdelete.view"}, function() {
              removediv.fadeOut("slow",function() {
                  removediv.remove();
                  //verify if is the only-child.
                  if ($("div[name='"+section+"']").length == 0) {
                    $("h4."+section).fadeOut("slow");
                    var theselect = document.forms["filtro"].filter;
                    theselect.options.length = 0;
                    theselect.style.background = "#fff";
                    document.location.href = "index.view";                         
                  }  
              });
         });
        }
        return false;
   });
}
function initCitations() {
  var citations = $(".citation");
  if (citations.length <= 0) return;
  var html = "";
  var rnd = Math.floor(citations.length*Math.random());
  for (var i = 0; i < citations.length; i++) {
    if(i == rnd) {
        citations.eq(i).css("display","block");
        break;
    }
  }
}

var homeNewsSlideShow = {

	items : 0,
	
	newsBoxes : 0,
	
	slideshowMargin : 0,
	
	page : 1,
	
	slides : [],
	
	fadeOutTime : 200,
	
	fadeInTime : 200,
	
	stopTime : 12000,
	
	slide : function() {

		homeNewsSlideShow.slideInterval = setInterval(homeNewsSlideShow.slideToPage, (homeNewsSlideShow.fadeOutTime + homeNewsSlideShow.fadeInTime + homeNewsSlideShow.stopTime));
		
	},
	
	slideToPage : function() {
		
		var page = homeNewsSlideShow.page;
		
		homeNewsSlideShow.page++;
		if(homeNewsSlideShow.page > homeNewsSlideShow.items)
			homeNewsSlideShow.page = 1;
			
		for(var i = 0; i < homeNewsSlideShow.newsBoxes; i++) {
			
			if(homeNewsSlideShow.slides[(page - 1)][i])
				homeNewsSlideShow.slides[(page - 1)][i].fadeOut(homeNewsSlideShow.fadeOutTime, function() {
					
					var slide = $(this).attr("bs:slide") * 1;
					homeNewsSlideShow.slides[(homeNewsSlideShow.page - 1)][slide].fadeIn(homeNewsSlideShow.fadeInTime);
					homeNewsSlideShow.updatePager();
					
				});

		}//for
		
	},
	
	goToPage : function(to_page) {
		
		if(homeNewsSlideShow.slideInterval) {
			clearInterval(homeNewsSlideShow.slideInterval);
			homeNewsSlideShow.slideInterval = null;
		}
		
		var page = homeNewsSlideShow.page;
		homeNewsSlideShow.page = to_page;

		for(var i = 0; i < homeNewsSlideShow.newsBoxes; i++) {
			
			if(homeNewsSlideShow.slides[(page - 1)][i])
				homeNewsSlideShow.slides[(page - 1)][i].fadeOut(homeNewsSlideShow.fadeOutTime, function() {
					
					var slide = $(this).attr("bs:slide") * 1;
					homeNewsSlideShow.slides[(homeNewsSlideShow.page - 1)][slide].fadeIn(homeNewsSlideShow.fadeInTime);
					homeNewsSlideShow.updatePager();
					
				});

		}//for

	},
	
	next : function() {
		
		page = homeNewsSlideShow.page + 1;
		
		if(page > homeNewsSlideShow.items)
			page = 1;
		
		homeNewsSlideShow.goToPage(page);
		
	},
	
	prev : function() {

		page = homeNewsSlideShow.page - 1;
		
		if(page < 1)
			page = homeNewsSlideShow.items;
		
		homeNewsSlideShow.goToPage(page);
		
	},
	
	updatePager : function() {
		
		var pages = homeNewsSlideShow.pager.children("A");
		
		for(var i = 0; i < pages.length; i++) {
			
			var page = $(pages[i]);
			page.removeClass("current");
			
			if(homeNewsSlideShow.page == (i+1))
				page.addClass("current");
			
		}
	
	},
	
	init : function() {
		
		if($(".slideshow")) {
			
			var slideshow = $(".slideshow");
			
			var elencoNews = slideshow.children(".elenco-news");
			
			this.newsBoxes = elencoNews.length;
			
			for(var i = 0; i < elencoNews.length; i++) {
				
				var elencoNewsChild = $(elencoNews[i]);
				var contentBoxes = elencoNewsChild.children(".content-box");
				
				if(contentBoxes.length > this.items)
					this.items = contentBoxes.length;
				
				for(var j = 0; j < contentBoxes.length; j++) {
					
					var contentBoxesChild = $(contentBoxes[j]);

					if(j > 0)
						contentBoxesChild.css({"display" : "none"});
					
				}//for
				
			}//for
			
			if(this.items > 1) {

				this.pager = $("#slide-pager");
				
				for(var i = 0; i < this.items; i++) {
					
					for(var j = 0; j < elencoNews.length; j++) {
						
						var elencoNewsChild = $(elencoNews[j]);
						var contentBoxes = elencoNewsChild.children(".content-box");
						
						if(!this.slides[i])
							this.slides[i] = new Array();
						
						if(contentBoxes[i]) {
							this.slides[i][j] = $(contentBoxes[i]);
							this.slides[i][j].attr({"bs:page" : i, "bs:slide" : j});
						}
						
					}
				
					if(i == (this.page-1))
						this.pager.append('<a class="current" href="javascript:homeNewsSlideShow.goToPage('  + (i+1) + ');" title="">' + (i+1) + '</a>');
					else
						this.pager.append('<a href="javascript:homeNewsSlideShow.goToPage('  + (i+1) + ');" title="">' + (i+1) + '</a>');
					
				}
				
				this.slide();
				
			}//if
			
		}//if
		
	}//f
	
};


$(document).ready(function(){
	homeNewsSlideShow.init();
	//rndNews();
	rndProjects();
	tabs();
	filettos();
	footer();
	tinyImgSwf();
	waterfallSelects();
	populateSchool();
	peopleTooltips();
	ieSelectionBugFix();
	initFavourites();
	initCitations(); 
});
