﻿/* CM Santana */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

/* returns a specific attribute from the URL */
$.extend({
  getUrlVars: function() {
    var vars = [], hash;
    var hashes = window.location.href.slice( window.location.href.indexOf( '?' ) + 1 ).split( '&' );
    for( var i = 0; i < hashes.length; i++ ) {
      hash = hashes[i].split( '=' );
      vars.push( hash[0] );
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function( name ) {
    return $.getUrlVars()[name];
  }
});

$(function() {
    correctMenus("#mainmenu");

    /* clear background on home */
    var homeID = $.getUrlVar( "ID" );
    if( homeID == 10 || !homeID )
        $( "#maincontainer" ).css( "background" , "none" );


    /* group calendar events with days */
    if( $( ".calendardate" ).length )
      fixCalendar_v2();
        //fixGroupCalendar();

    /* Files */
/*
    if( $( ".FilesDates" ).length ) {
        $( ".FilesDates ul li a" ).each( function() {
            $( this ).attr( "href" , "javascript:FolderContent( 'camara_" + $( this ).attr( "title" ) + "', " + $( this ).attr( "title" ) + ",  'FilesDates' );" );
        });
    }
    if( $( ".FilesDatesAssembly" ).length ) {
        $( ".FilesDatesAssembly ul li a" ).each( function() {
            $( this ).attr( "href" , "javascript:FolderContent( 'assembleia_" + $( this ).attr( "title" ) + "', " + $( this ).attr( "title" ) + ", 'FilesDatesAssembly' );" );
        });
    }
*/

    // fix last item main menu, 1º level
    $( '#mainmenu ul li.lastitem' ).addClass( 'lastfirstlevel' );

    /* fix width first and last li element from main menu */
    /* last item */
    $( '#mainmenu ul li.lastitem .M1 li a' ).each( function() {
        $( this ).width( $( this ).width() - 15  );
    });
    /* first item */
    $( '#mainmenu ul li.firstitem .M1 li a' ).each( function() {
        $( this ).width( $( this ).width() - 15  );
    });
    $( '#mainmenu ul li.firstitem .M1 li a' ).css( "margin-left" , "15px" );

    /* --- end fix width --- */

    /* fix  path menu */
    if( $( '.path' ).length )
        $( '.path ul li a:last' ).css( "border" , "none" );

    /* fix max width img flipbook */
    if( $( '.flipBookHome tr td img' ).length ) {
        $( '.flipBookHome tr td img' ).each( function() {
            if( $( this ).width() > 100 )
                $( this ).width( 100 );
        });
    }

    // Open/close links
    $( "table.openCloseBar" ).parents( "div.Paragraph" ).find( "div.ParagraphModule" ).hide();
    $( "table.openCloseBar a" ).click( function() {
        $( this ).parent().find( "a" ).toggle();
        $( this ).parents( "div.Paragraph" ).find( "div.ParagraphModule" ).slideToggle();
    });

    // correct news paging
    $( ".destaquepages a b, .pages a b" ).parent().css({ "padding-left" : "0" , "padding-right" : "0" });

    // sets up the containers that have the docs background image
    if( $(".docsBackground").length ) {
      $(".docsBackground").each( function() {
        if( $( this ).find( 'img' ).length == 0 )
          $( this ).find( 'span' ).css( 'padding-left', '99px' );
      });
      $(".docsBackground").hover( function () {
        $( this ).find( 'span' ).css( 'text-decoration', 'underline' );
      },
      function() {
        $( this ).find( 'span' ).css( 'text-decoration', 'none' );
      });
    }

    // check if the clicked news of the homepage needs to be opened on a popup window
    $( '.useFlipBook a' ).click( function() {
      if( $( this ).parent().find( '.openPopup .target' ).text().indexOf( "blank" ) != -1 ) {
        window.open( $( this ).parent().find( '.openPopup .url' ).text(), '_blank', 'width=796, height=610, resizable=no' );
        return false;
      }
    });

    // initialize scrollable together with the navigator plugin
    if( $( '.scrollable' ).length )
      $( '#browsable' ).scrollable().navigator();

    // set to active the first news from the homepage
    if( $( '#destaque' ).length ) {
      $( '#destaque .destaquetitle:first, #destaque .destaquepagging a:first' ).addClass( 'active' );
      $( '#destaque .destaquetitle:not( :first )' ).css( 'display', 'none' );
    }

    // fade the corresponding news text from the homepage after changing the image
    if( $( '.destaquepagging' ).length ) {
      $( '.destaquepagging .navi a' ).click( function() {
        var selectedNewsNumber = parseInt( $( this ).text() );

        $( '#destaque .destaquetitle.active' ).fadeOut( function() {
          $( this ).removeClass( 'active' );
          $( '#destaque .destaquetitle' ).eq( selectedNewsNumber - 1 ).fadeIn( function() {
            $( this ).addClass( 'active' );
          });
        });
      });
    }
});


/* animation for calendar */
function animeCalendar() {
    $( ".calendardate a" ).each( function( i ) {
        $( this ).click( function() {
            $( ".event" ).slideUp();
            $( ".event:eq(" + i + ")" ).slideDown();
        });
    });
    $( ".calendardate a:first" ).trigger( "click" );
}

/* group calendar events with days */
function fixGroupCalendar() {
    var calendarArray = [],
       calendarObject = {},
       html_date = "<ul>",
       html_event = "";

    $( ".calendardate" ).each( function( i ) {
        calendarObject = { day: parseInt( $( this ).find( '.calendarDay' ).text() ), month: $( this ).find( '.calendarMonth' ).text(),
                           hour: $( ".eventNumb_" + ( i + 1 ) + " .calendarday span" ).text(), title: $( ".eventNumb_" + ( i + 1 ) + " .calendarhappening span" ).text(),
                           href: $( ".eventNumb_" + ( i + 1 ) + " .calendarhappening a" ).attr( "href" ), indent: $( ".eventNumb_" + ( i + 1 ) + " .calendarhappening a" ).attr( "class" ),
                           hrefTitle: $( ".eventNumb_" + ( i + 1 ) + " .calendarhappening a" ).text() };

        if( calendarArray.length == 0 ) {
            calendarArray.push( calendarObject );
            html_date += "<li><div class='calendardate calendarCount_" + ( i + 1 ) + "' ><a href='#'><span class='calendarDay'>" + calendarObject.day + "</span><br /><span class='calendarMonth'>" + calendarObject.month + "</span></a></div></li>";
            html_event += "<div class='event eventNumb_" + ( i + 1 ) + "'><div class='calendarday'>" + calendarObject.day + " " + calendarObject.month + " | <span> " + calendarObject.hour + "</span></div><div class='calendarhappening'><span>" + calendarObject.title + "</span> <a href='" + calendarObject.href + "' class='" + calendarObject.indent + "' title='" + calendarObject.title + "'>" + calendarObject.hrefTitle + "</a></div></div>";
        }
        else {
           var foundDate = false;

            for( var y = 0; y < calendarArray.length; y++ ) {
                if( calendarObject.day == calendarArray[ y ].day && calendarObject.month == calendarArray[ y ].month ) {
                    if( calendarArray.length <= 6 ) {
                        html_event = html_event.substr( 0 , html_event.length - 6 );
                        html_event += "<div class='calendarday'>" + calendarObject.day + " " + calendarObject.month + "</div><div class='calendarhappening'> " + calendarObject.title + " <a href='" + calendarObject.href + "' class='" + calendarObject.indent + "' title='" + calendarObject.title + "'>" + calendarObject.hrefTitle + "</a></div></div>";
                    }
                    foundDate = true;
                }
            }
            if( !foundDate ) {
                calendarArray.push( calendarObject );
                if( calendarArray.length <= 6  ) {
                    html_date += "<li><div class='calendardate calendarCount_" + i + "' ><a href='#'><span class='calendarDay'>" + calendarObject.day + "</span><br /><span class='calendarMonth'>" + calendarObject.month + "</span></a></div></li>";
                    html_event += "<div class='event eventNumb_" + ( i + 1 ) + "'><div class='calendarday'>" + calendarObject.day + " " + calendarObject.month + " | <span> " + calendarObject.hour + "</span></div><div class='calendarhappening'><span>" + calendarObject.title + "</span> <a href='" + calendarObject.href + "' class='" + calendarObject.indent + "' title='" + calendarObject.title + "'>" + calendarObject.hrefTitle + "</a></div></div>";
                }
            }
        }
    });
    html_date += "</ul>";
    $( "#calendarlist ul" ).remove();
    $( "#calendarlist" ).html( html_date );
    $( "#calendarprogram div" ).remove();
    $( "#calendarprogram" ).html( html_event );
    animeCalendar();
}

function fixCalendar_v2() {
  $("#calendarlist ul li").each(function(i) {
    //if (i<6) $(this).css('display','inline');
    if (i<6) $(this).show();
  });
  $("#calendarlist ul li a:first").trigger("click");
}

function showDayEvents(clickedClass) {
  $("#calendarlist ul li a").removeClass("activeDay");
  $("#calendarlist ul li." + clickedClass + " a").addClass("activeDay");
  
  $("#calendarprogram li:not(." + clickedClass + ")").slideUp("slow");
  $("#calendarprogram li." + clickedClass).slideDown("slow");
}

/* create list itens for quick News */
function flashNews( fieldClass, columnSize, classItem, appendClass ) {
    var count = 0,
        htmlCode = "",
        loopElements = true,
        imageArray = [],
        imageObject = {},
        elementsPerColumn = 0;

    $( "." + fieldClass ).each( function( i ) {
        imageArray[ i ] = imageObject = { href: $( this ).attr( 'href' ), title: $( this ).attr( 'title' ) };
    });

    /*
       to know how many elements need to be placed on each column, get the total number of elements that have the class passed by the
       parameter "fieldClass", divide for the desired number of columns passed by the "columnSize" parameter and round it up.
    */
    elementsPerColumn = Math.round( $( "." + fieldClass ).length / columnSize );

    while( loopElements ) {
        for( i = 0; i < columnSize; i++ ) {
            htmlCode += "<div class='infobottom'><ul>";
            //for( y = 0; y < sizeList; y++ ) {
            for( y = 0; y < elementsPerColumn ; y++ ) {
                if( count > imageArray.length )
                    y += 100000;

                if( count < imageArray.length )
                    htmlCode += "<li><div class='quickNewsTitle' style='width: 20px; height: 100%;'>" + ( count + 1 ) + ".</div> <a href='" + imageArray[ count ].href + "' title='" +  imageArray[ count ].title + "' >" + imageArray[ count ].title + "</a></li>";

                count++;
            }
            if( count > imageArray.length )
                i += 100000;

            htmlCode += "</ul></div>";
        }
        htmlCode += "<div style='clear: both;' ></div>";
        ( count > imageArray.length ) ? loopElements = false : loopElements = true;
    }

    $( classItem ).remove();
    $( appendClass ).append( htmlCode );

    /* fix height after creating the elements */
    var maxHeight = 0;

    $( classItem +  " ul li" ).each( function() {
        if( maxHeight < $( this ).height() )
            maxHeight  = $( this ).height()
    });

    $( classItem + " ul li" ).height( maxHeight );
}


/* correct menus */
function correctMenus( selector ) {

    var menuWidth = $( selector ).width(),
        totalLiWidth = 0,
        $li = $( selector + " > ul > li" );

    $li.each(function() {
        totalLiWidth += $( this ).outerWidth( true );
    });

    // Work out how much padding we need and account for rounding errors, the error is going to be forced into the first tab.
    var requiredPadding = Math.floor((( menuWidth - totalLiWidth) / $li.length ) / 2 ),
        leftRoundingErrorFix = Math.round(( menuWidth - (( requiredPadding * $li.length * 2 ) + totalLiWidth )) / 2 ),
        rightRoundingErrorFix = Math.floor(( menuWidth - (( requiredPadding * $li.length * 2 ) + totalLiWidth )) / 2 );

    // Apply padding to list items
    $li.each( function( i ) {
        ( i == 1 ) ? $(this).find("a").css('padding-left',requiredPadding+leftRoundingErrorFix+'px').css('padding-right',requiredPadding+rightRoundingErrorFix+'px') : $(this).find("a").css('padding-left',requiredPadding+'px').css('padding-right',requiredPadding+'px');
    });

    $( selector + " .M1" ).each(function() {
        $(this).find( "li" ).css({
            "padding" : "10px 0px",
            "width": $( this ).parent().find( "a:first" ).outerWidth( true )+ "px"
        });
        $( this ).find( "a" ).css({
            "padding" : "10px 10px",
            "width": ( parseInt( $( this ).parent().find( "a:first" ).outerWidth( true )) - 20 - 4 ) + "px"
        });
    });


    //Safari and Chrome correction
    if($.browser.safari || $.browser.chrome) {
        $(selector + " ul").css("display", "block");
        $(selector + " li").css("display", "list-item");
    }

    $( '#mainmenu ul:first > li' ).bind( 'mouseover' , jsddm_open );
    $( '#mainmenu ul:first > li' ).bind( 'mouseout',  jsddm_timer );
}

function jsddm_canceltimer() {
    if( closetimer ) {
        window.clearTimeout( closetimer );
        closetimer = null;
    }
}

function jsddm_close() {
    if( ddmenuitem ) ddmenuitem.css( 'visibility' , 'hidden' );
}

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $( this ).find( 'ul' ).eq( 0 ).css( {'visibility':'visible','z-index':'500'} );
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

/* clears the general search box text */
function clearField( input, defaultValue ) {
    if( $('#'+input).val().toLowerCase() == defaultValue.toLowerCase() )
        $('#'+input).val("");
}
/* checks if the general search box value isn't empty or if its not equal to the default value */
function ValidateSearch( input, errorMessage, defaultValue ) {
    if( ( $( '#' + input ).val() == "" ) || ( $( '#' + input ).val().toLowerCase() == defaultValue.toLowerCase() ) ) {
        alert( errorMessage );
        return false;
    }
}

/* resets the general search box text to its default value */
function checkIfEmpty( input, defaultValue ) {
    if( ( $( '#' + input ).val() == "" ) || $( '#' + input ).val().toLowerCase() == defaultValue.toLowerCase() )
        $( '#' + input ).val( defaultValue );
}

/* current folder content */
var current = 0, currentYear = 0;


/* folder content ajax */
function FolderContent( folder , year, id ) {
    $.ajax({
        url: location.protocol + "//" + location.hostname + "/files/getfoldercontents.aspx?path=/Files/Filer/PDFs/deliberacoesTodos/" + folder,
        success: function( data ) {
            var xml;

            if( $.browser.msie && typeof data == "string" ) {
                xml = new ActiveXObject( "Microsoft.XMLDOM" );
                xml.async = false;
                xml.loadXML( data );
            }
            else {
                xml = data;
            }

            if( current != 0 || current != folder ) {
                $( ".Files_" + current ).slideUp( 850, function() {
                        $( this ).remove();
                        
                });
            }
            $( "." + id + " ul li a[title=" + year + "]" ).text( "[ " + year + " ]" );
            $( "." + id + " ul li a[title=" + year + "]" ).addClass( "activeFolder" );

            if( current != 0 ) {
                $( "." + id + " ul li a[title=" + currentYear + "]" ).text( currentYear );
                $( "." + id + " ul li a[title=" + currentYear + "]" ).removeClass( "activeFolder" );

            }

            current = folder;
            currentYear = year;

            var exist;
            ( $( ".Files_" + folder ).length ) ? exist = true : exist = false;

            if( !exist && xml ) {
                var html = "<ul class='Files_" + folder + "'>\n";

                $( xml ).find( "File" ).each( function() {
                    html += "<li>\n<a href='" + $( this ).attr( 'href' ) + "' title='" + $( this ).attr( 'title' ) + "'>" + ( $( this ).attr( 'title' ).substr( 0 , $( this ).attr( 'title' ).length - 4 ) ) + "</a>\n</li>\n";
                });
                html += "<ul/>\n";
                $( '.FilesYear' ).append( html );
                $( ".Files_" + folder ).slideDown( 850 );
            }
            else {
                if( exist ) {
                    $( ".Files_" + folder ).slideUp( 850, function() {
                        $( this ).remove();
                    });
                }
            }
        }
    });
}

/* Global Executive Program */
var previousIndex = 99, currentClick = false;

/* Executive Program */
$( document ).ready( function() {
    if( $( ".openClose" ).length ) {
        $( ".openClose a" ).click( function() {
            /* get current index of the element */
            var index = $( ".openClose a" ).index( this );

            /* this opens the current element and closes the previous if a previous element was open */
            if( index !== previousIndex ) {
                $( this ).text( "Fechar" );
                $( ".hiddenTable" ).eq( index ).show();

                if( $( ".openClose a" ).length >= previousIndex ) {
                    $( ".openClose a" ).eq( previousIndex ).text( "Abrir" );
                    $( ".hiddenTable" ).eq( previousIndex ).hide();
                }
                /* reset the current click */
                currentClick = false;
            }

            /* else "if" the same element is click this function toggles throw open/close */
            if( $( ".openClose a" ).length >= previousIndex && index === previousIndex ) {
                if( !currentClick ) {
                    $( this ).text( "Abrir" );
                    $( ".hiddenTable" ).eq( index ).hide();
                    currentClick = true;
                }
                else {
                    $( this ).text( "Fechar" );
                    $( ".hiddenTable" ).eq( index ).show();
                    currentClick = false;
                }
            }
            /* save last position open */
            previousIndex = index;
        });
    }
    $( ".openClose a[name=" + $.getUrlVar( "NewsID" ) + "]" ).trigger( "click" );
});


/* home overlay */
function buildOverlay( image ) {
    $( "body" ).append( "<div class='overlayElement'><img src='" + image + "' alt='top'/></div>" );
    $( ".overlayElement" ).overlay({
        top: '10%',
        closeOnClick: true,
        closeOnEsc: true,
        fixed: false,
        load: true
    });
    $( ".close" ).text( "X fechar" );
}

/* overlay Home Page */
function displayOverlay( image ) {
    if( $( '.overlayElement' ).length ) {
        $( '.overlayElement img' ).attr( "src" , image );
        $( '.overlayElement' ).overlay().load();
    }
    else {
        buildOverlay( image );
        $( '.overlayElement' ).overlay().load();
    }
}

