var hasChangedUC = false;
 
// NEW SLIDER START
function slider(parentId,slideId){
	$(document).ready(function(){
		// Slider nav
		var sliderNav = [
			'<ul class="slider_nav">', 
			'<li class="slider_prev"><a href="#" title="Previous">Previous</a></li>', 
			'<li class="slider_next"><a href="#" title="Next">Next</a></li>',
			'</ul>'
		].join("");
		
		// Append the nav to the slider container
		$(parentId).append(sliderNav);
		
		// Append the pagination to the slider container
		$(parentId).append('<div class="slider_pager">');
		
		// Append the pause button to the slider container
		$(parentId).append('<a class="slider_pause" title="Pause">Pause</a>');
		
		// Toggle the pause button to pause/play
		$('.slider_pause').toggle(function() { 
			// Pause functionality
            $(slideId).cycle('pause');
	        	$(this).addClass('play');
	        	var title = "Play";
	       		$(this).attr('text',title); 
	       		$(this).attr('title',title); 
            }, function() { 
			// Play functionality
            $(slideId).cycle('resume', true); 
            	$(this).removeClass('play');
            	var title = "Pause";
           		$(this).attr('text',title); 
           		$(this).attr('title',title); 
        }); 
        		
		// Attach the slide behaviour
		$(slideId)
		.cycle({ 
			fx:     'fade',
			speed:  500,
			timeout: 5000,
			pause:   1,
			next:   '.slider_next',
			prev:   '.slider_prev',
			pager:  '.slider_pager'
		});
	});
} 
// NEW SLIDER END

function printUnderConstruction(txt) {
	
	try {
		if (txt) {
			$("#pr_alertDiv_span").html(txt);
			hasChangedUC = true;
		}
	} catch(e) {}	
    var newTop = parseInt(200 + window.scrollY);    
    $("#pr_alertDiv").css('top','' + newTop + 'px');
    $("#pr_alertDiv").fadeIn();
}

function closeUnderConstruction() {
	$("#pr_alertDiv").fadeOut();
	if (hasChangedUC) {
		$("#pr_alertDiv_span").html('Functionality under construction');
		hasChangedUC = false;
	}
}
function showSuggestion(i){
    var div = "#suggestion-"+i;
    var img = "#image-"+i;
    var display = $(div).css("display");
    var arrow;      
    if(display == 'none'){                
        $(div).css("display","block");
        $(img).attr("src",imgPath+"/icone/arrow_open.gif");
    }else{
        $(div).css("display","none");
        $(img).attr("src",imgPath+"/icone/arrow_close.gif");
    }
}
var periodOrder = {"w":0,"m":1,"y":2}
function comparePeriods(periodOne, periodTwo){
   //Period is composited by a letter (w per week, m per month, y per year) and a number. Eg. w12 or m20 or y2
   //The order is w < m < y.
   //Return -1 if periodOne < periodTwo.
   //        0 if periodOne = periodTwo.
   //        1 if periodOne > periodTwo
   var periodOneChar = periodOrder[periodOne.substring(0,1)];
   var periodTwoChar = periodOrder[periodTwo.substring(0,1)];
   var periodOneDigit = parseInt(periodOne.substring(1,periodOne.length));
   var periodTwoDigit = parseInt(periodTwo.substring(1,periodTwo.length));

   if(periodOneChar < periodTwoChar){
      return -1;
   } else if(periodOneChar > periodTwoChar){
      return 1;
   } else {
      if(periodOneDigit < periodTwoDigit){
	     return -1;
	  }else if(periodOneDigit > periodTwoDigit){
	     return 1;
	  }else{
	     return 0;
	  }
   }
}

function votePoll(currentNodePath, controllerDiv, pollId, keyPollDidntChoose, from) {

    var voteValue = parseInt($("#choisediv_" + pollId + " input[name='vote']:checked").val(), 10);

    if (isNaN(voteValue)) {
        openAlerterAlertDiv(keyPollDidntChoose);
        return;
    }
    
    $('#' + controllerDiv).load('' + currentNodePath + '.process_vote.html',{
        ':operation': 'nop',
        '_charset_' : 'utf-8',
        'from' 		: from,
        'vote'      : '' + voteValue
    });
}
// PNG FIX
function pngFix() {
 var arVersion = navigator.appVersion.split("MSIE")
 var version = parseFloat(arVersion[1])
 if ((version >= 5.5) && (document.body.filters)) 
 {
    for(var i=0; i<document.images.length; i++)
    {
       var img = document.images[i]
       var imgName = img.src.toUpperCase()
       if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
       {
          var imgID = (img.id) ? "id='" + img.id + "' " : ""
          var imgClass = (img.className) ? "class='" + img.className + "' " : ""
          var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
          var imgStyle = "display:inline-block;" + img.style.cssText 
          if (img.align == "left") imgStyle = "float:left;" + imgStyle
          if (img.align == "right") imgStyle = "float:right;" + imgStyle
          if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
          var strNewHTML = "<span " + imgID + imgClass + imgTitle
          + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
          + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
          + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
          img.outerHTML = strNewHTML
          i = i-1
       }
    }
 }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function panelMenuShow(status) {
    //$(".home-panel-menu").fadeTo("fast", (status ? 1 : 0));
    //$(".home-panel-menu").css("display", (status ? "block" : "none"));
	$(".home-panel-menu").css("width", (status ? "100%" : "0px"));    
}

if ($) {
 $(document).ready(function(){
  // PNG FIX Launch
  pngFix();
 });
}
function doLogout(logoutUrl, backUrl){
    $.ajax({url: logoutUrl,success:function(){top.location.href=backUrl;}});
}
var call = 0;
function initJumper()
{
    var curPos      = 0;
    var totalPanels = $(".jumpToList").size();
    
    $("#jumpToSlider").css("marginLeft", "0px");
    $("#jumpToSlider").css("width", totalPanels*415+"px");
    function change(direction) 
    {
            call = call + 1;
            if (direction)
            {
                if (curPos < (totalPanels -1))
                {
                    curPos++;

                    var leftValue = $("#jumpToSlider").css("marginLeft");
                    var movement  = parseFloat(leftValue, 10) - 415 + "px";
                    
                    $("#jumpToSlider")
                        .stop()
                        .animate({
                            marginLeft: movement
                        }, 1000);
                }
            }
            else
            {       
                if (curPos > 0)
                {
                    curPos--;

                    var leftValue = $("#jumpToSlider").css("marginLeft");
                    var movement  = parseFloat(leftValue, 10) + 415 + "px";
                    
                    $("#jumpToSlider")
                        .stop()
                        .animate({
                            marginLeft: movement
                        }, 1000);
                }
            }
    }
        
    //when the left/right arrows are clicked
      $(".right").click(function(){ change(true); }); 
      $(".left").click(function(){ change(false); });
   
    $(window).keydown(function(event)
    {
      switch (event.keyCode) 
      {
            case 37: //left arrow
                $(".left").click();
                break;
            case 39: //right arrow
                $(".right").click();
                break;
      }
    });
};
/*
 * numero della palla
 * url da aprire
 * selettore (W M Y N)
 * 
 * SPOSTATA NELLA JSP DEL COMPONENTE PER PERMETTERE DI EFFETTUARE IL REDIRECT A CONTEXT 
 * 
 * 
function changePage(ballNumber, url, selector) {
    //alert('ballNumber: ' + ballNumber + ' url: ' + url + ' selector: ' + selector);
    document.location.href='' + url;
}
*/


//Internet Explorer and Mozilla-based browsers refer to the Flash application 
//object differently.
//This function returns the appropriate reference, depending on the browser.
function getFlexApp(appName) {
    if (navigator.appName.indexOf ("Microsoft") !=-1) {
        return window[appName];
    } else {
        return document[appName];
    }
}


function switchFlap(flap, imgSize) {
    if (flap != activeFlap) {
        var activeFlapClass = 'flap0' + activeFlap + '_on';
        var activeFlapNewClass = 'flap0' + activeFlap + '_off';
        var inactiveFlapClass = 'flap0' + flap + '_off';
        var inactiveFlapNewClass = 'flap0' + flap + '_on';
        
        var activeDiv = $('.' + activeFlapClass);
        var inactiveDiv = $('.' + inactiveFlapClass);

        var activeImageSrc = pathToImg + '/2flap0' + activeFlap + imgSize + '_on.gif';
        var activeImageNewSrc = pathToImg + '/2flap0' + activeFlap + imgSize + '_off.gif';

        var inactiveImageSrc = pathToImg + '/2flap0' + flap + imgSize + '_off.gif';
        var inactiveImageNewSrc = pathToImg + '/2flap0' + flap + imgSize + '_on.gif';

        var activeImg = $('.' + activeFlapClass + ' img');
        var inactiveImg = $('.' + inactiveFlapClass + ' img');


        activeDiv.removeClass(activeFlapClass);
        activeDiv.addClass(activeFlapNewClass);

        inactiveDiv.removeClass(inactiveFlapClass);
        inactiveDiv.addClass(inactiveFlapNewClass);

        
        activeImg.attr("src", activeImageNewSrc);
        inactiveImg.attr("src", inactiveImageNewSrc);
       
        activeFlap = flap;
        //console.log("flap: "+activeFlap);
        //if(activeFlap == 3){
        //  $('#flashNavigatorObj').css('visibility','hidden');
        //  $('#thirdTab').show();
        //  switchMenu(flap);
        //}else{
        //  $('#flashNavigatorObj').css('visibility','visible');
        //  $('#thirdTab').hide();
            switchMenu(flap);
        //}
    }
}

function switchMenu(tab) {
    //console.log(getFlexApp('flashNavigatorObj'));
    getFlexApp('flashNavigatorObj').switchMenu(tab);
    //console.log(getFlexApp('flashNavigatorObj').switchMenu(tab));
}
