﻿// DETECTS IF NAMESPACE OF THE APP EXISTS, CREATES THE NAMESPACE OF THE APP.
if (!SB) var SB = {};
else if (SB && typeof (SB) != "object")
    throw new Error("SB is not an Object type");

/* SB.UI
* All user inteface under this class name
*/
SB.UI = {};

SB.UI.RunCodeBeforeAnyEventBindingViaJquery = function () {
    (function () {
        // remove layerX and layerY
        var all = $.event.props,
			len = all.length,
			res = [];
        while (len--) {
            var el = all[len];
            if (el != 'layerX' && el != 'layerY') res.push(el);
        }
        $.event.props = res;
    } ());
}



/* SB.UI.initFancyBox 
* INIT FANCYBOX ON THE LANDING PAGE FOR TERMS AND CONDITIONS 
*
*/
SB.UI.initFancyBox = function () {

    $(".popupLanding").fancybox({
        'padding': 0,
        'autoScale': true,
        'transitionIn': 'none',
        'transitionOut': 'none'
    });

    setTimeout('SB.UI.cssFancyBox();', 1000);

}


SB.UI.initIframeFancyBox = function () {


    //    $('.popup').bind('click', function () {
    //        $('#wrapp_1').remove();
    //    })
    var callTheCallBack = false,
        videoObj = null;

    $(".popup").fancybox({
        'type': 'iframe',
        'width': 640,
        'height': 600,
        'padding': 0,
        'autoScale': true,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'onComplete': function () {

            //console.log('tou aqui!!!!!!!!!!!!!!!!!!!!');
            videoObj = $('#wrapp').find('object');

            if (videoObj.length) {
                videoObj[0].PauseVideo();
            }
            else {
                callTheCallBack = true;

                function theCb() {
                    videoObj = $('#wrapp').find('object');                    

                    if (videoObj.length && typeof videoObj[0].PauseVideo == 'function') {
                        //console.log('---> ', videoObj[0]);
                        //console.log('---> ', videoObj[0].PauseVideo);
                        setTimeout(function () {
                            videoObj[0].PauseVideo();
                        }, 1200);
                        
                    }
                    else {
                        if (callTheCallBack)
                            setTimeout(function () { theCb(); }, 250);
                    }
                }

                theCb();
            }


            $('#fancybox-frame').load(function () {
              
                var elIframe = $('#fancybox-frame')[0];


                // PUB SUB IN IFRAME CONTENT WINDOW.
                elIframe.contentWindow.SB.UI.initSlideShowThumbs();
            });
        },
        'onClosed': function () {
            callTheCallBack = false;

            if (videoObj && videoObj.length) {
                videoObj[0].PlayVideo();
                videoObj = null;
            }


            $('#wrapp').show();
            //  $('#wrapp_1').html(sliderHomePage);


            //  setTimeout('SB.UI.initSlideShowThumbs();', 1000);


        }
    });

    setTimeout('SB.UI.cssFancyBox();', 1000);



}

/* SB.UI.cssFancyBox 
* CHANGE BACKGROUND OF FANCYBOX
*
*/
SB.UI.cssFancyBox = function () {
    $('#fancybox-outer').css('background', '#fff');

}

SB.UI.selectLanguage = function () {

    $('.languagesLanding li').bind('click', function () {

        $('.languagesLanding li').removeClass('selected');
        $(this).addClass('selected');

        sTextAnchor = $(this).find('a').text();
        
        if (sTextAnchor != 'PORTUGUÊS') {
            $('.termsAndConditions').hide();
        } else {
            $('.termsAndConditions').show();
        }

        return false;
    })

}

/* SB.UI.DinamicTabs 
* Create the tabs for the title of the section's in homepage and other pages; and the submenu of the section's, 
* for example on the 17º SBSR -> INFO UTIL; and calculate the with of the title section to extend the the background
*
*/
SB.UI.DinamicTabs = function () {

    var aIdTitle = [],
        aIdSubTitle = [],
        aIdContent = [],
        aIdSubContent = [],
        aIdSubTitle2 = [],
        aIdSubContent2 = [];

    $('.titleModule ul').each(function (index) {
        ulId = $(this).attr('id');
        aIdTitle.push(ulId);

        divId = $(this).parents('.tabSectionPage').find('.contentTabsSection').attr('id');
        aIdContent.push(divId);

        SB.UI.TabsSite(aIdContent[index], aIdTitle[index]);
        SB.UI.initCalculateWidth(aIdTitle[index]);

    })

    $('.submenuModule ul ').each(function (index) {
        ulId = $(this).attr('id');
        aIdSubTitle.push(ulId);

        divId = $(this).parents('.submenuModule').find('.contentSubTabsSection').attr('id');
        aIdSubContent.push(divId);
        SB.UI.TabsSite(aIdSubContent[index], aIdSubTitle[index]);
    });
}

/* SB.UI.TabsSite 
* Create tabs for all the site
*
* Params: [DOM Element] contentId - string of div that contains the content of the tab
* Params: [DOM Element] ulId - string of the parent ul class
*/
SB.UI.TabsSite = function (contentId, ulId) {

    var tabContainers = $('div#' + contentId + ' > div ');

    tabContainers.hide().filter(':first').show();

    $(' ul#' + ulId + ' li:not(.disabled) a').click(function () {

        tabContainers.hide();

        tabContainers.filter(this.hash).show();
        $(' ul#' + ulId + ' a').removeClass('selected');
        $(' ul#' + ulId + ' li').removeClass('selected');
        $(this).addClass('selected');
        $(this).parent().addClass('selected');

        SB.UI.EqualHeight($(".colum"));

        var elHref = $(this).attr('href');

        switch (elHref) {
            case '#onlineParticipation':
                iPhaseSelected = $('#experienceList option:selected').attr('value');

                SB.ACCOUNT.GetParticipationsWeb(iPhaseSelected);
                SB.ACCOUNT.GetDateInterval(iPhaseSelected);

                $('.selectForParticipationsWeb').bind('click', function () {

                    iPhaseSelected = $('#experienceList option:selected').attr('value');

                    sIdDateSelected = $('#seeAllParticipations_container li.selected').attr('id');
                    splitSIdDateSelected = sIdDateSelected.split('_');

                    SB.ACCOUNT.ChangeResultParticipationWebByInterval(iPhaseSelected, splitSIdDateSelected[2]);

                }).click;

                break;
            case '#totalParticipation':
                iPhaseSelected = $('#experienceList option:selected').attr('value');
                SB.ACCOUNT.GetParticipations(iPhaseSelected);

                sElSelected = $('#experienceList_input_' + iPhaseSelected).text();
                $('#totalParticipation em').text(sElSelected);
                break;

            case '#smsTotal':

                iPhaseSelected = $('#experienceList option:selected').attr('value');

                SB.ACCOUNT.GetUserMobilePhones(iPhaseSelected);
                SB.ACCOUNT.GetParticipationsSms('0', iPhaseSelected);

                $('.selectForParticipationsSms').bind('click', function () {

                    iPhoneSelected = $('#seeAllParticipationsSms_container li.selected').attr('id');
                    splitIPhoneSelected = iPhoneSelected.split('_');

                    SB.ACCOUNT.GetParticipationsSms(splitIPhoneSelected[2], iPhaseSelected);

                }).click;
                break;
        }


//        if (elHref == '#onlineParticipation') {
//            iPhaseSelected = $('#experienceList option:selected').attr('value');

//            SB.ACCOUNT.GetParticipationsWeb(iPhaseSelected);
//            SB.ACCOUNT.GetDateInterval(iPhaseSelected);

//            $('.selectForParticipationsWeb').bind('click', function () {

//                iPhaseSelected = $('#experienceList option:selected').attr('value');

//                sIdDateSelected = $('#seeAllParticipations_container li.selected').attr('id');
//                splitSIdDateSelected = sIdDateSelected.split('_');

//                SB.ACCOUNT.ChangeResultParticipationWebByInterval(iPhaseSelected, splitSIdDateSelected[2]);

//            }).click;


//        } else if (elHref == '#totalParticipation') {
//            iPhaseSelected = $('#experienceList option:selected').attr('value');

//            SB.ACCOUNT.GetParticipations(iPhaseSelected);

//        }
//        else if (elHref == '#smsTotal') {
//            iPhaseSelected = $('#experienceList option:selected').attr('value');

//            SB.ACCOUNT.GetUserMobilePhones(iPhaseSelected);
//            SB.ACCOUNT.GetParticipationsSms('0', iPhaseSelected);

//            $('.selectForParticipationsSms').bind('click', function () {

//                iPhoneSelected = $('#seeAllParticipationsSms_container li.selected').attr('id');
//                splitIPhoneSelected = iPhoneSelected.split('_');

//                SB.ACCOUNT.GetParticipationsSms(splitIPhoneSelected[2], iPhaseSelected);

//            }).click;
//        }

        elClassLink = $(this).attr('override');

        if (elClassLink == 'notTab') {
            return true;
        } else {
            return false;
        }

    }).filter(':first').click();
}

/* SB.UI.TimerTabContent 
* init scrolltop event and show the comment added on the film premiere of the week, and hide the message that appears when submit form.
*
*/
SB.UI.TimerTabContent = function () {
    $(window).scrollTop(950);
    setTimeout(function () {
        $('.addComment').attr('style', 'display:block');
        $('.postResultMessage').attr('style', 'display:none');
    }, 5000);
}


/* SB.UI.initCalculateWidth 
* calculates the width of a li trough the sum of all lis, subtracting the width to the ul, placing the background that is missing.
* Params: [DOM Element] ulId - string of the parent ul class
*
*/
SB.UI.initCalculateWidth = function (ulId) {

    var aLiWidth = [],
        iCountLiWidth = 0,
        iulWidth,
        iLiBg = 0;

    $('#' + ulId + ' li').each(function (index) {
        liWidth = $(this).width();
        aLiWidth.push(liWidth);
        iCountLiWidth += aLiWidth[index];
    });

    iulWidth = $('#' + ulId).width();
    iLiBg = (iulWidth - iCountLiWidth);

    $('#' + ulId + ' li.lastBg').css('width', iLiBg + 'px');
}

/* SB.UI.showVideoOnslideShowThumbs 
* mix video and images in the slideshow of the homepage.
*
* Params: [DOM Element] elLiVideo - string of the li with the video
*
*/

SB.UI.showVideoOnslideShowThumbs = function (elLiVideo, id, player, params, width, height) {

    //alert('video -> ', elLiVideo);

    var elVideoInfo = $(elLiVideo).find('.videoObject');

    var sVideoId = elVideoInfo.attr('videoid'),
        sElementId = elVideoInfo.attr('id');

    var elLiContainer = elVideoInfo.parent('li');
    var elSliderId = elLiContainer.attr('id') + '_f';

    if (id) {
        //console.log('--> ', id, $(id));
        $('#' + id).prepend('<div id="' + id + '_son"></div>');
        id += '_son';
    }
    //preloader doesn't work :( /swf/Preloader.swf
    //if (sVideoId) {	
    	if (player === undefined) {
			player = '/swf/videoPlayerYoutube.swf';
		}
		
		if (params === undefined) {
			params = { 
	    			youtubeId: sVideoId, 
	    			autoStart: true, 
	    			flashId: elSliderId 
	    	};
		}

        swfLoad(
            id || 'videoContainer',
            player,
            player,
            elSliderId,
            'transparent',
            '#00000',
            width || 584,
            height || 312,
          	params,
            false
	    );
    /*}
    else {
    	console.log('n havia svideoid');
    }*/
};

/* SB.UI.modVideoAlone 
* video player standalone.
*
* Params: [DOM Element] el - jquery object of the container
*
*/
SB.UI.modVideoAlone = function(el) {
    var element = $(el),
        elId = element.attr('id'),
        sVideoId = element.find('.idVideoAlone').attr('videoId'),
        sImgThumb = element.find('.imgVideoAlone').attr('src');

    swfLoad('wrapVideoAlone', '/swf/videoPlayerYoutube.swf', '/swf/videoPlayerYoutube.swf', elId, 'transparent', '#00000', 584, 312, { youtubeId: sVideoId, autoStart: true, flashId: elId }, false);
};

/* SB.UI.initSlideShowThumbs 
* init slideshow with thumbs of the homepage and other pages
*
*/
SB.UI.initSlideShowThumbs = function () {

    

    var elAutoSlide = $('.imageSlideShow').attr('autoslide');

    // THIS IS TO APPLY DIFF BORDER MASKS TO THE IMAGE FRAME AND IMAGE THUMB
    var aMaskDefault = [
        "url(/images/icons/Frame-off-default.png) no-repeat 0 0",
        "url(/images/icons/Frame-on-default.png) no-repeat 0 0"
    ];


    var aMaskMud = [
        "url(/images/icons/Frame-off.png) no-repeat left top",
        "url(/images/icons/Frame-on.png) no-repeat left top"
    ];

    var sImgFrameOff = aMaskDefault[0],
        sImgFrameOn = aMaskDefault[1],
        elMudMask = $('.MudMask');

    if (elMudMask.length) {
        sImgFrameOff = aMaskMud[0];
        sImgFrameOn = aMaskMud[1];
    }

    // INIT SLIDESHOW WITH OPTIONS
    $("div#fewoptions").slideViewerPro({
        thumbs: 4,
        thumbsPercentReduction: 24,
        galBorderWidth: 0,
        galBorderColor: "",
        thumbsTopMargin: 6,
        thumbsRightMargin: 8,
        thumbsBorderColor: sImgFrameOff,
        thumbsActiveBorderColor: sImgFrameOn,
        thumbsActiveBorderOpacity: 1,
        thumbsBorderOpacity: 0,
        buttonsTextColor: "#000000",
        leftButtonInner: "<img src='/images/icons/slide-prev.png' />",
        rightButtonInner: "<img src='/images/icons/slide-next.png' />",
        autoslide: elAutoSlide == 'true',
        typo: true,
        typoFullOpacity: 0.7,
        asTimer: 6000
    });
};


/* SB.UI.initCalendarEvent 
* init the calendar with events
*
*/
SB.UI.CalendarEvent = function () {
    var currentPosition = 0,
        slideWidth = $('#slideInner').width() + 1,
        slides = $('.slide'),
        numberOfSlides = slides.length;

    $('.month').html(aMonth[0]);

    // Remove scrollbar in JS
    $('#slidesContainer').css('overflow', 'hidden');

    // Wrap all .slides with #slideInner div
    slides.wrapAll('<div id="slideInner"></div>')
    // Float left to display horizontally, readjust .slides width
	.css({
	    'float': 'left',
	    'width': slideWidth
	});

    // Set #slideInner width equal to total width of all slides
    $('#slideInner').css('width', slideWidth * numberOfSlides);

    // Insert controls in the DOM
    $('.controls')
    .prepend('<span class="control left" id="leftControl">Clicking moves left</span>')
    .append('<span class="control right" id="rightControl">Clicking moves right</span>');

    // Hide left arrow control on first load
    ManageControls(currentPosition);

    var bLeft = false,
    	bRight = true;
    // Create event listeners for .controls clicks

    $('.dayToday').click(function () {

        var elToday = $('.today'),
            elSlideToday = elToday.parents('.slide'),
            iSlideToday = elSlideToday.index();  // Determine the position of the element today

        $('#slideInner').animate({
            'marginLeft': slideWidth * (-iSlideToday)
        });

        $('.month').html(aMonth[iSlideToday]);

        ManageControls(iSlideToday);

        currentPosition = iSlideToday;
    })

    $('.control').bind('click', function () {

        if (((bLeft == true) && ($(this).attr('id') == 'leftControl')) || ((bRight == true) && ($(this).attr('id') == 'rightControl'))) {
            // Determine new position
            currentPosition = ($(this).attr('id') == 'rightControl') ? currentPosition + 1 : currentPosition - 1;

            // Hide / show controls
            ManageControls(currentPosition);

            // Move slideInner using margin-left
            $('#slideInner').animate({
                'marginLeft': slideWidth * (-currentPosition)
            });

            $('.month').html(aMonth[currentPosition]);

            $('.blockHover').removeClass('selected');
            $('.blockHover').hide();
        }
    })

    /* Function ManageControls  
    * Hides and Shows controls depending on currentPosition
    *
    * Params: [DOM Element] position - number that represents the position of the month
    */
    function ManageControls(position) {

        // Hide left arrow if position is first slide
        if (position == 0) {
            bLeft = false;
            $('#leftControl').removeClass('left');
            $('#leftControl').addClass('leftOff');
            $('.leftOff').css('cursor', 'default')
        } else {
            bLeft = true;
            $('#leftControl').removeClass('leftOff');
            $('#leftControl').addClass('left');
            $('.left').css('cursor', 'pointer')
        }

        // Hide right arrow if position is last slide
        if (position == numberOfSlides - 1) {
            bRight = false;
            $('#rightControl').removeClass('right');
            $('#rightControl').addClass('rightOff');
            $('.rightOff').css('cursor', 'default')
        } else {
            bRight = true;
            $('#rightControl').removeClass('rightOff');
            $('#rightControl').addClass('right');
            $('.right').css('cursor', 'pointer')
        }
    }

}


/* SB.UI.GetInfoEventCalendar 
* Get info event by calling the information by ajax, with a service of server side
*
* Params: [DOM Element] id - string of the element mouseover
*/
SB.UI.GetInfoEventCalendar = function (id) {
    var aEvent = [],
        crrEvent = {},
        aIdPopup = [],
        bFound = false,

        iPopupid = $('#' + id).attr('popupid'),
        urlService = '/base/services/getCalendarEvent/' + iPopupid,
	    method = 'GET',
        title = '',
        date = '',
        summary = '',
        image = '',
        elLoading = '<img src="../images/icons/ajax-loader.gif" alt="loading" />';

    $('.contentEvent').html(elLoading)

    aPosition = $('#' + id).position()

    calendarWidth = $('.slide').width();

    idSplit = id.split('_');
    idBlock = 'block_' + idSplit[1];
    $('.blockHover').attr('id', idBlock);

    if (aPosition.left < calendarWidth / 2) {
        $('#' + idBlock).css({ 'left': (aPosition.left + 30) + 'px', 'top': (aPosition.top + 75) + 'px' });
    } else {
        $('#' + idBlock).css({ 'left': (aPosition.left - 60) + 'px', 'top': (aPosition.top + 75) + 'px' });
    }

    $('#' + idBlock).show();

    if (aEvent.length == 0) {

        $.ajax({
            type: method,
            url: urlService,
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            success: function (calendarEvent) {
                title = calendarEvent.Title;
                date = calendarEvent.FormattedDate;
                summary = calendarEvent.Summary;
                image = calendarEvent.Image;

                crrEvent = [
							{
							    id: iPopupid,
							    titleEvent: title,
							    formattedDate: date,
							    summaryEvent: summary,
							    ImageEvent: image
							}
						]

                aEvent.push(crrEvent)

                html = '<cite>' + date + '</cite>';
                html += '<h2>' + title + '</h2>';
                if (image != null) {
                    html += '<em><img src="' + image + '" alt="' + title + '"/></em>';
                }
                html += '<span>' + summary + '</span>';
                html += '<div class="clear"></div>';

                $('.contentEvent').html(html)

            },
            error: function (data) {
                //  console.log(data)
            }
        })

    } else {
        for (i = 1; i <= aEvent.length; i++) {

            if (aEvent[i - 1][0].id == iPopupid) {

                date = aEvent[i - 1][0].formattedDate;
                title = aEvent[i - 1][0].titleEvent;
                image = aEvent[i - 1][0].ImageEvent;
                summary = aEvent[i - 1][0].summaryEvent;

                html = '<cite>' + date + '</cite>';
                html += '<h2>' + title + '</h2>';
                if (image != null) {
                    html += '<em><img src="' + image + '" alt="' + title + '"/></em>';
                }
                html += '<span>' + summary + '</span>';
                html += '<div class="clear"></div>';

                $('.contentEvent').html(html)

                bFound = true;
                break;

            } else {
                bFound = false;
            }
        }

        if (bFound == false) {
            $.ajax({
                type: method,
                url: urlService,
                contentType: "application/json; charset=utf-8",
                dataType: "json",

                success: function (calendarEvent) {
                    title = calendarEvent.Title;
                    date = calendarEvent.FormattedDate;
                    summary = calendarEvent.Summary;
                    image = calendarEvent.Image;

                    crrEvent = [
						{
						    id: iPopupid,
						    titleEvent: title,
						    formattedDate: date,
						    summaryEvent: summary,
						    ImageEvent: image
						}
					]

                    aEvent.push(crrEvent)

                    html = '<cite>' + date + '</cite>';
                    html += '<h2>' + title + '</h2>';
                    if (image != null) {
                        html += '<em><img src="' + image + '" alt="' + title + '"/></em>';
                    }
                    html += '<span>' + summary + '</span>';
                    html += '<div class="clear"></div>';

                    $('.contentEvent').html(html)
                }
            });
        }
    }
}

/* SB.UI.ShowEventCalendar 
* Show the event content on mouseover
*
*/
SB.UI.ShowEventCalendar = function () {
    $('.slide a').hover(
        function () {
            aId = $(this).attr('id');
            SB.UI.GetInfoEventCalendar(aId);
        },
        function () {
            $('.blockHover').hide();
        });
}

/* SB.UI.GetEventsForCalendarAngola
* Show the events of calendar angola
*
*/
SB.UI.GetEventsForCalendarAngola = function () {

    var urlService = '/base/services/getUpcomingAngolaCalendarEvents/4378',
	    method = 'GET',
        elEventContent = $('.contentEventAngola'),
        aContentEvent = [],
        iLimitCharacters = 85;

    $.ajax({
        type: method,
        url: urlService,
        dataType: "xml",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        success:
		    function (xml) {

			    $(xml).find('AngolaCalendar').each(function (index) {

				    var $contentEvents = $(this);

				    $contentEvents.find('UpcomingEvent').each(function () {
				        var $contentInfo = $(this),

				        categoryEvent = $contentInfo.find('Category').text(),
                        titleEvent = $contentInfo.find('Title').text(),
                        dateEvent = $contentInfo.find('Date').text(),
                        summaryEvent = $contentInfo.find('Summary').text(),
                        linkEvent = $contentInfo.find('Link').text();

				        summaryEvent = summaryEvent.substr(0, iLimitCharacters);

				        dateEvent = dateEvent.split(' ');

				        str = dateEvent[0];

				        number = str.search("-");

				        for (i = 0; i < number; i++) {
				            str = str.replace("-", ".");
				        }

				        aContentEvent.push('<div class="eventCategory">');
				        aContentEvent.push('<span class="catDate">' + categoryEvent + ' <cite> - ' + str + '</cite></span>');
				        aContentEvent.push('<span class="title">' + titleEvent + '</span>');
				        aContentEvent.push('<span class="summary">' + summaryEvent + '(...)' + '</span>');
				        aContentEvent.push('<a href="' + linkEvent + '" class="linkEvent">' + titleEvent + '</a>');
				        aContentEvent.push('</div>');
				    });

				    elEventContent.html(aContentEvent.join(''));
			    });
		    }
    })
}

SB.UI.paginateAngolaCalendar = function () {

    inumberEvents = $('.contentEventAngola .eventCategory').length;
    iPages = inumberEvents / 2;

    $('#pagerEvent').aqPaging({
        current: 1,
        pages: iPages,
        pagerMax: 3,
        flip: true,
        style: 2,
        itemsPerPage: 3,
        objToPaginate: $('.contentEventAngola')

    })


}



/* SB.UI.EqualHeight 
* PUT THE SAME HEIGHT ON THE COLUMS
*
* Params: [DOM Element] group - string of the group that has the equal height
*/
SB.UI.EqualHeight = function (group) {
    //set the starting bigestHeight variable
    $('.colum').attr('style', '');

    var tallest = 0;
    //check each of them
    group.each(function () {
        //if the height of the current element is  
        //bigger then the current biggestHeight value  
        var thisHeight = $(this).height();
        if (thisHeight > tallest) {

            if ($('.colum').length) {
                tallest = thisHeight + 150;
            } else {
                tallest = thisHeight;
            }
        }
    });
    //update the biggestHeight with the  
    //height of the current elements  
    group.height(tallest);
}

/* SB.UI.PaginationResult 
* Method that creates a pagination for result page
*
*/
SB.UI.PaginationResult = function () {
    $("#paginationList").pagination($('.contentListItems'), {
        items_per_page: 2,
        num_edge_entries: 2,
        num_display_entries: 3,
        prev_text: "",
        next_text: "",
        prev_show_always: false,
        next_show_always: false,
        callback: pageselectCallback
    });
}

/* SB.UI.initSlideShowWithYoutubeVideos 
* Method that creates a slideshow just for youtube videos
*
*/
SB.UI.InitSlideShowWithYoutubeVideos = function () {

    $("ul.thumbsYoutube").ytplaylist({
        addThumbs: false,
        autoPlay: false,
        holderId: 'youtubeVideo',
        playerHeight: '356',
        playerWidth: '590',
        allowFullScreen: false
    });

    var numberOfSlides = $('.thumbsYoutube li').length;
    if (numberOfSlides == 1) {
        $('.contentThumbsYoutube').hide()
    } else {
        $('.contentThumbsYoutube').show()
    }

    SB.UI.SlideShowWithYoutubeVideos();
}


/* SB.UI.SlideShowWithYoutubeVideos 
* Method that creates a slideshow just for youtube videos and put the left and right navigation
*
*/
SB.UI.SlideShowWithYoutubeVideos = function () {
    var iDivision,
        currentPosition = 0,
        slideWidth = 588,
        slides = $('.thumbsYoutube li'),
        numberOfSlides = slides.length,
        slidesPerBlock = 4;

    // Remove scrollbar in JS
    $('.containerVideos').css('overflow', 'hidden');

    // Set #slideInner width equal to total width of all slides
    $('.thumbsYoutube').css('width', slideWidth * (numberOfSlides / slidesPerBlock));

    // Insert controls in the DOM
    $('.controlsSlideYoutube')
    .prepend('<span id="leftControlYoutube" class="controlYoutube"></span>')
    .append('<span id="rightControlYoutube" class="controlYoutube"></span>');

    // Hide left arrow control on first load
    manageControls(currentPosition);

    var bLeft = bRight = true;

    // Create event listeners for .controls clicks
    $('.controlYoutube').bind('click', function () {

        // Determine new position
        currentPosition = ($(this).attr('id') == 'rightControlYoutube') ? currentPosition + 1 : currentPosition - 1;

        liAll = $('.containerVideos ul li').size();
        iDivision = liAll / 4;

        // Hide / show controls
        manageControls(currentPosition);

        // Move slideInner using margin-left
        $('.thumbsYoutube').animate({
            'marginLeft': slideWidth * (-currentPosition)
        });
    });

    // manageControls: Hides and Shows controls depending on currentPosition
    function manageControls(position) {
        // Hide left arrow if position is first slide
        if (position == 0) {
            $('#leftControlYoutube').hide()
        } else {
            $('#leftControlYoutube').show()
        }
        // Hide right arrow if position is last slide
        if (position > iDivision - 1 || position == iDivision - 1 || numberOfSlides < 5) {
            $('#rightControlYoutube').hide()
        } else {
            $('#rightControlYoutube').show()
        }
    }
}


/* SB.UI.RatingStarList 
* Method that get the rating value and send that value to the page, and disabled that rating
*
*/
SB.UI.RatingStarList = function () {

    var urlPage = $('.vote').attr('lang');

    $('.auto-submit-star').rating({
        enabled: true,
        required: true,
        callback: function (value, link) {
            // 'this' is the hidden form element holding the current value
            // 'value' is the value selected
            // 'element' points to the link element that received the click.

            urlPage = urlPage.replace('[RatingValue]', value);
            $('.vote').attr('lang', urlPage);

            fnReadOnly();

            $.ajax({
                url: urlPage
            });
        }
    });

    function fnReadOnly() {
        $('.auto-submit-star').rating('disable');
    }
}

/* SB.UI.MovieRating 
* INIT MOVIE RATING, DISABLE ALL INPUTS, SETS CHECKED ACCORDING TO LANG ATTR
*
*/
SB.UI.MovieRating = function () {
    var urlPage = $('.vote').attr('lang');

    $('.userRating').find('div').removeClass('star-rating-on');
    $('.userRating input[type=radio]').each(function () {
        $(this).removeAttr('checked');
    });

    $('.user-star-rate').rating({
        enabled: true,
        required: true,
        callback: function (value, link) {
            // 'this' is the hidden form element holding the current value
            // 'value' is the value selected
            // 'element' points to the link element that received the click.

            urlPage = urlPage.replace('[RatingValue]', value);
            $('.vote').attr('lang', urlPage);

            fnCinemaReadOnly();

            $.ajax({
                url: urlPage
            });
        }
    });

    function fnCinemaReadOnly() {
        $('.user-star-rate').rating('disable');
        var elMovieVote = $('.movieRating .voteNumber');
        var iVoteHtml = Number(elMovieVote.html()) + 1;
        elMovieVote.html(iVoteHtml);
    }

    var iMovieRate = $('.voteMovie').attr('lang');

    $('.auto-star-rate').filter(':nth-child(' + iMovieRate + ')').attr('checked', 'checked');

    $('.auto-star-rate').rating({
        enabled: true,
        required: true
    });
}

/* SB.UI.initAccordion 
* INIT METHOD ACCORDION
*
*/
SB.UI.initAccordion = function () {

    $('.linkAcc h3').click(function () {

        $('.linkAcc h3').css({ 'border-bottom-width': '1px', 'border-bottom-color': '#000000', 'border-bottom-style': 'solid' });

        if ($(this).parents('.rowBlock').next().is('.open')) {
            $(this).parents('.rowBlock').next().slideUp('slow', function () {
                $(this).css({ 'border-bottom': 'none' });
                SB.UI.EqualHeight($(".colum"));
            }).removeClass('open');

            $('.linkAcc h3').removeClass('active');

        } else {

            $(this).parents('.customAcc').find('.open').slideUp('slow');

            $('.linkAcc h3').removeClass('active').parents('.rowBlock').next().slideUp('slow').removeClass('open');
            $(this).addClass('active').css({ 'border-bottom': 'none' });

            $(this).parents('.rowBlock').next().slideDown('slow', function () {

                $(this).css({ 'border-bottom-width': '1px', 'border-bottom-color': '#000000', 'border-bottom-style': 'solid' });

                SB.UI.EqualHeight($(".colum"));

                var elIframe = $('.googlemaps', $(this));

            }).addClass('open');
        }
        return false;
    })

}

/* SB.UI.showVideoDetailBand 
* SHOW THE VIDEO BAND WHEN CLICK ON VIDEO
*
*/
SB.UI.showVideoDetailBand = function () {

    $('.listVideos li').click(function () {
        $('.listVideos li').removeClass('selected');
        var elLi = $(this),
                elSpan = $('> span', elLi),
                sVideoId = elSpan.attr('videocode'),
                elVideoHolder = $('.videoBand'),
                elImgHolder = $('.imageBand');

        var aObjVideo = [
               '<div class="objectBand"><object width="588" height="364">',
               '<param name="movie" value="http://www.youtube.com/v/' + sVideoId + '?fs=1&amp;hl=en_GB&amp;showinfo=0&amp;autoplay=1" />',
               '<param name="allowFullScreen" value="true" />',
                '<param name="allowscriptaccess" value="always" />',
                '<param name="wmode" value="transparent" />',
                '<embed src="http://www.youtube.com/v/' + sVideoId + '?fs=1&amp;hl=en_GB&amp;showinfo=0&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" wmode="transparent" allowfullscreen="true" width="588" height="364"></embed>',
                '</object></div> '
                ];

        elImgHolder.fadeOut('slow', function () {
            elVideoHolder.empty().show().append(aObjVideo.join(''));

        });
        $(this).addClass('selected');
        if(document.Mp3Player)
            document['Mp3Player'].stop();
    })
}

/* SB.UI.InitGalleryImages 
* init gallery images and put arrows navigations
*
*/
SB.UI.InitGalleryImages = function () {

    var aUrlImageGallery = [],
		bFound = false;

    $('.thumbs li a').each(function (i) {

        var elUrl = $(this).attr('url'),
            urlPage = window.location.href;

        aUrlImageGallery.push(elUrl);

        $('.thumbs li').removeClass('selected')

        if (aUrlImageGallery[i] == urlPage) {
            srcImage = $(this).attr('title');
            slipSrcImage = srcImage.split('-')

            SB.UI.showGalleryImages();
            $.galleriffic.gotoImage(slipSrcImage[1]);

            $(this).parent('li').addClass('selected')

            bFound = true;
            return false;
        } else {
            bFound = false;
        }
    })

    if (bFound == false) {
        SB.UI.showGalleryImages();
    }

    $('#thumbs, .navigation').removeAttr("filter");
    window.setTimeout(function () {
        $('#thumbs, .navigation').attr('style', '');
        $('#thumbs, .navigation').removeAttr("filter");
    }, 500);

    window.setTimeout(function () {
        $('#thumbs, .navigation').attr('style', '');
        $('#thumbs, .navigation').removeAttr("filter");
    }, 3000);
}


/* SB.UI.showGalleryImages 
* REMOVE THE IMAGE AND SHOW THE VIDEO WITH THE CORRECT CODE
*
*/
SB.UI.showGalleryImages = function () {
    iThumbLength = $('#thumbs li').length
    // Initialize Advanced Galleriffic Gallery
    $('#thumbs').galleriffic({
        delay: 2000,
        numThumbs: 8,
        preloadAhead: 0,
        enableTopPager: false,
        enableBottomPager: true,
        maxPagesToShow: $('#thumbs li').length,
        imageContainerSel: '#slideshow',
        controlsContainerSel: '#controls',
        captionContainerSel: '#caption',
        loadingContainerSel: '#loading',
        renderSSControls: false,
        renderNavControls: false,
        enableKeyboardNavigation: false,
        enableHistory: false,
        autoStart: false,
        syncTransitions: false,
        defaultTransitionDuration: 500,
        onSlideChange: function (prevIndex, nextIndex) {
            // 'this' refers to the gallery, which is an extension of $('#thumbs')
            this.find('ul.thumbs').children()
            //.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(prevIndex).fadeTo('fast').end()
							.eq(nextIndex).fadeTo('fast', 1.0);
        },
        onPageTransitionOut: function (callback) {
            this.fadeTo('fast', 1.0, callback);
        },
        onPageTransitionIn: function () {
            this.fadeTo('fast', 1.0);
        }

    });

}

/* SB.UI.InitFancyBox
* init method fancybox
*
*/
SB.UI.InitFancyBox = function () {
    if ($('.modalWindow').length) {
        $(".modalWindow").fancybox({
            'padding': 0,
            'width': 660,
            'autoDimensions': false,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'onComplete': function () {
                SB.UI.hideButton();
            }
        });
    }
}

/* SB.UI.HideButton
* method to hide buttons on pages that are open by fancybox, with class "modalWindow"
*
*/
SB.UI.HideButton = function () {
    if ($('.fancyBoxItens').length) {
        $('.buttonBack').remove();
    }
}

/* SB.UI.ChangeUrlFbLike
* mehod that changes the url facebook like, by click on diferente image at the gallery image and tha flash pages
*
* Params: [DOM Element] url - string of url facebook page
*
*/
SB.UI.ChangeUrlFbLike = function (url) {
    sUrl = url;
    url = "http://www.facebook.com/plugins/like.php?channel_url=http%3A%2F%2Fstatic.ak.fbcdn.net%2Fconnect%2Fxd_proxy.php%3Fversion%3D0%23cb%3Df2a853fc846474a%26origin%3Dhttp%253A%252F%252Flocalhost%253A52433%252Ff243b8898053b36%26relation%3Dparent.parent%26transport%3Dpostmessage&font=lucida%20grande&href=" + sUrl + "&layout=button_count&locale=pt_PT&node_type=link&sdk=joey&show_faces=false&width=90";

    if ($('.likeGallery').length) {
        $('.likeGallery').children().find('iframe').attr('src', url);
    }

    if ($('.btnLikeFb').length) {
        $('.btnLikeFb').children().find('iframe').attr('src', url);
    }
}

/* getCoordinates
* mehod that get the coordinates of an object, and is called from flash
*
* Params: [DOM Element] x - horizontal position number
* Params: [DOM Element] y - vertical position number
*
*/
function getCoordinates(x, y) {
    $('.btnLikeFb').css('left', x)
    $('.btnLikeFb').css('top', y)
}

/* SB.UI.InitLogin
* INITIALIZE LOGIN FUNCTIONALITIES
*
* Params: [DOM Element] param - string to know if the page make "reload"
* Params: [DOM Element] panelShowError - content to show the errors
*
*/
SB.UI.InitLogin = function (param, panelShowError) {

    var elLinkLogin = $('a.linkLogin'),
		elLoginPanel = $('div.loginPopin'),
		elLoginSection = $('div.loginPanel'),
		elLinkPanels = elLoginPanel.find('.linkLoginPanel'),
		oLinkPos = elLinkLogin.position(),
		iPosLeft = (oLinkPos.left) - 100;

    // PLACE LOGIN PANEL IN CORRECT LEFT POSITION ACCORDING TO LINK LOGIN POSITION.		
    elLoginPanel.css({ 'left': +iPosLeft + 'px' });

    if (param != 'reload') {

        elLinkLogin.bind('click', linkLoginHandler);
        elLinkPanels.bind('click', linkPanelHandler);

    } else {
        elLoginPanel.show();

        // IF ERROR MESSG IN PANEL ERRORS DISPLAY PANEL
        if (typeof panelShowError != 'undefined') {

            if (panelShowError == 'displayErrorPass' || panelShowError == 'displayErrorReg') {
                $('.' + panelShowError).parents('.loginPanel').show();
            }
        }
    }

    // LINK LOGIN CLICK EVENT HANDLER.
    function linkLoginHandler(e) {

        var elLoginPanel = $('div.loginPopin'),
			elThis = $(this),
            href = jQuery(location).attr('href');

        elLoginSection.hide();
        elLinkPanels.removeClass('btnLightBrownSelected');

        if (elLoginPanel.css('display') == 'none') {

            elThis.addClass('linkLoginSelected');
            elLoginPanel.show();
        } else {

            elThis.removeClass('linkLoginSelected');
            elLoginPanel.hide();
        }



        e.preventDefault();
        e.stopPropagation();
    }

    // LINK LOGIN PANELS EVENT HANDLER.
    function linkPanelHandler(e) {

        var elThis = $(this),
			elCurrSection = elThis.next('.loginPanel');

        if (elCurrSection.css('display') == 'none') {

            elThis.addClass('btnLightBrownSelected');
            elLoginSection.hide();
            elCurrSection.show();

        } else {

            elThis.removeClass('btnLightBrownSelected');
            elCurrSection.hide();

        }

        e.preventDefault();
        e.stopPropagation();
    }

    // DOCUMENT MOUSEUP EVENT HANDLER, WHEN CLICKED OUTSIDE LOGIN AREA, HIDE LOGIN AREA.
    $(document).mouseup(function (e) {
        if ($(e.target).parents('div.blockLoginRegister').length == 0) {
            elLoginPanel.hide();
        }
    });

    SB.UI.InitLoginValues();
}

/* SB.UI.InitLoginValues
* Init the label default value of inputs at content Login
*
*/
SB.UI.InitLoginValues = function () {
    SB.UI.initLabelDefaultValue('.loginPopin input[type=text]');
    SB.UI.initLabelDefaultValue('.loginPopin input[type=password]');
}

/* SB.UI.initLabelDefaultValue
* FUNCTION THAT SHOW HIDES INPUT LABEL IN ABSOLUTE POSITION, RECEIVES JQUERY DOM ELEMENT IN STRING TO INITIALIZE EVENTS.
*
* Params: [DOM Element] el - input selector
*
*/
SB.UI.initLabelDefaultValue = function (el) {
    var inputSelectors = jQuery(el);
    var labelSelectors = inputSelectors.prev('label');

    inputSelectors.each(function () {
        var elInput = jQuery(this);
        var elLabel = elInput.prev('label');
        if (elInput.val() != '') {
            elLabel.addClass('labelHidden');
        }
    });
    inputSelectors.focus(function (e) {
        var elLabel = jQuery(this).prev('label');
        if (jQuery(this).val() == '') {
            elLabel.addClass('labelHidden');
        }
        e.stopPropagation();
    });
    inputSelectors.blur(function (e) {
        var elLabel = jQuery(this).prev('label');
        if (jQuery(this).val() == "") {
            elLabel.removeClass('labelHidden');
        }
        e.stopPropagation();
    });
    labelSelectors.click(function (e) {
        jQuery(this).next('input').trigger('focus');
        jQuery(this).next('textarea').trigger('focus');
        e.preventDefault();
        e.stopPropagation();
    });
}


/* SB.UI.initPartnerLogin
* Inicializes the popup login when click on the hobby of partners cinema.
*
*/
SB.UI.initPartnerLogin = function () {
    var elPartnerA = $('a.partnerLogin'),
        elLinkLogin = $('a.linkLogin');

    elPartnerA.click(function (e) {
        elLinkLogin.trigger('click');
        e.preventDefault();
        e.stopPropagation();
    });
}


/* SB.UI.initWhenLogged
* INITIALIZE LOGOUT AND REGISTER
*
*/
SB.UI.initWhenLogged = function () {

//    if (typeof SB.SA != 'undefined') {
//        SB.SA.GetParticipations();
//        SB.SA.GetParticipationsWeb();
//        SB.SA.GetParticipationsSms();
//    }



    //------//
    SB.UI.initLogoutAndRegister();
    SB.UI.initScrollText();
}


/* SB.UI.initLogoutAndRegister
* INITIALIZE LOGOUT AND REGISTER
*
* Params: [DOM Element] param - string to know if the page make "reload"
* Params: [DOM Element] panelShowError - content to show the errors
*
*/
SB.UI.initLogoutAndRegister = function (param, panelShowError) {
    var elLinkLogin = $('a.loggedLinks'),
		elLoginPanel = $('div.logoutAndRegisterPopin'),
		oLinkPos = elLinkLogin.position(),
		iPosLeft = (oLinkPos.left) - 60;

    // PLACE LOGIN PANEL IN CORRECT LEFT POSITION ACCORDING TO LINK LOGIN POSITION.		
    elLoginPanel.css({ 'left': +iPosLeft + 'px' });

    if (param != 'reload') {

        elLinkLogin.bind('click', linkLoginHandler);

    } else {
        elLoginPanel.show();

        // IF ERROR MESSG IN PANEL ERRORS DISPLAY PANEL
        if (typeof panelShowError != 'undefined') {

            if (panelShowError == 'displayErrorPass' || panelShowError == 'displayErrorReg') {
                $('.' + panelShowError).parents('.loginPanel').show();
            }
        }
    }

    // LINK LOGIN CLICK EVENT HANDLER.
    function linkLoginHandler(e) {

        var elLoginPanel = $('div.logoutAndRegisterPopin'),
			elThis = $(this);

        if (elLoginPanel.css('display') == 'none') {
            elLoginPanel.show();
        } else {
            elLoginPanel.hide();
        }

        e.preventDefault();
        e.stopPropagation();
    }

    // DOCUMENT MOUSEUP EVENT HANDLER, WHEN CLICKED OUTSIDE LOGIN AREA, HIDE LOGIN AREA.
    $(document).mouseup(function (e) {
        if ($(e.target).parents('div.blockLoginRegister').length == 0) {
            elLoginPanel.hide();
        }
    });

}

/* SB.UI.initScrollText
* WHEN SOMEONE LOGED IN, ON MOUSEOVER AT THE NAME, TRIGGER A MARQUEE, IN OTHER WORDS THE NAME SCROLLING
*
*/
SB.UI.initScrollText = function () {
    $('.scrollingtext').mouseover(function () {
        var elMouseOver = $(this);
        SB.UI.showMarquee(elMouseOver);
    }).mouseout(function () {
        var elMouseOver = $(this);
        var tw = $(this).width();
        elMouseOver.stop();
        elMouseOver.css({ left: 0 })
    });
}

/* SB.UI.showMarquee
* animate the username by making a marquee
*
* Params: [DOM Element] selector - selector to show marquee
*
*/
SB.UI.showMarquee = function (selector) {
    var ob = $(selector),
     tw = ob.width(),
     ww = ob.parent().width();

    if (ww < tw) {
        ob.animate({ left: '-' + ww + 'px' }, 6000, 'linear', function () {
            ob.trigger('marquee');
        });
    }
}

/* SB.UI.initPopinMail
* INIT POPIN EMAIL FOR CINEMA FICHA FILME
*
*/
SB.UI.initPopinMail = function () {
    SB.UI.initPopinMovieSendFriend();

    var elLinkPopin = $('.linkPopinMail'),
		elPopinMail = $('.popinMail');

    elLinkPopin.click(function (e) {
        var elThis = $(this);

        if (elPopinMail.is(':visible')) {
            elThis.removeClass('linkPopinActive');
            elPopinMail.hide();
        } else {
            elThis.addClass('linkPopinActive');
            elPopinMail.show();
        }
        e.preventDefault();
        e.stopPropagation();
    });
}

/* SB.UI.initPopinMovieSendFriend
* INIT POPIN EMAIL FOR CINEMA FICHA FILME
*
* Params: [DOM Element] param - string to know if the page make "reload"
*
*/
SB.UI.initPopinMovieSendFriend = function (param) {

    SB.UI.initLabelDefaultValue('.popinMail input[type=text], .popinMail textarea');

    if (param == 'reload') {
        var elPopinCinema = $('div.inviteEmail'),
			oPopinOffset = elPopinCinema.offset(),
			oPopinOffsetTop = Number(oPopinOffset.top) - 65;

        $('html, body').animate({ scrollTop: oPopinOffsetTop }, 50);
    }


    $('.popupUp').click(function () {

        $('.popinResult').hide();
        $('.popinContent').show();
        $('.popinMail textarea').attr('value', '');
        $('.popinMail input[type=text]').attr('value', '');
        SB.UI.initLabelDefaultValue('.popinMail input[type=text], .popinMail textarea');

        $('.popinContent input[type=text]').focus();
        $('.popinContent input[type=text]').blur();

        $('.popinContent textarea').focus();
        $('.popinContent textarea').blur();
        return false;
    });

    $('.closeButton').click(function () {

        $('.popinMail').fadeOut('slow', function () {
            $('.popinResult').hide();
            $('.popinContent').show();
            $('.popinMail textarea').attr('value', '');
            $('.popinMail input[type=text]').attr('value', '');
            SB.UI.initLabelDefaultValue('.popinMail input[type=text], .popinMail textarea');

            $('.popinContent input[type=text]').focus();
            $('.popinContent input[type=text]').blur();

            $('.popinContent textarea').focus();
            $('.popinContent textarea').blur();


        });

    })
}

/* SB.UI.participateHobby
* INIT POPIN EMAIL FOR CINEMA FICHA FILME
*
*/
SB.UI.participateHobby = function () {

    var elHobbyWrapper = $('div.hobbyWrapper'),
		elLinkContest = elHobbyWrapper.find('.linkTabContest'),
		elContentTabs = elHobbyWrapper.find('div.contentSubTabsSection'),
		oTabsPos = elContentTabs.position(),
		iTabsPosTop = oTabsPos.top,
		elTabContest = $('.tabParticipate'),
		elLinkTrigger = $('a.linkTriggerContest');


    elTabContest.css('top', iTabsPosTop + 'px');

    elLinkContest.bind('click', fnContestLink);
    elLinkTrigger.bind('click', fnTriggerContest);

    // EVENT HANDLER FOR THE TAB CONTEST, SHOW A USER CONTROL IN POS ABS.
    function fnContestLink(e) {

        var el = $(this),
			sElId = el.attr('id'),
			elParent = el.parent();

        if (sElId == 'linkContest1') {
            elTabContest.show();
        }
        else {
            if (!elParent.hasClass('disabled')) {
                elTabContest.hide();
            }
        }

        e.preventDefault();
        e.stopPropagation();
    }

    // TRIGGER THE LINK OF THE TAB CONTEST.
    function fnTriggerContest(e) {

        $('#linkContest1').trigger('click');

        var elSubTabsSection = $('div.hobbyWrapper div.tabHeader'),
			oTabsOffset = elSubTabsSection.offset(),
			iTabsOffsetTop = (oTabsOffset.top) - 65;

        $('html, body').animate({ scrollTop: iTabsOffsetTop }, 100);

        e.preventDefault();
        e.stopPropagation();
    }

    SB.UI.initLabelDefaultValue('.lineTextarea textarea');

    SB.UI.contestNonLogged();
}

/* SB.UI.contestNonLogged
* EVENT HANDLER FOR LINK USER NON LOGGED IN CONTEST CINEMA MUSIC
*
*/
SB.UI.contestNonLogged = function () {
    $('div.panelNonLogged a').click(function (e) {

        $('.loginPopin').show();

        e.preventDefault();
        e.stopPropagation();
    });
}

/* SB.UI.initWrapButton
* THIS FUNCTION WRAPS INPUT BUTTON WITH A SPECIFIC SPAN, TO MAKE ROUND CORNERS CSS.
*
*/
SB.UI.initWrapButton = function () {
    var elBtnRed1 = $('input.buttonRed1'),
		elBtnBordeaux = $('input.inputBordeaux'),
		elBtnWhite1 = $('input.buttonWhite1'),
		elNavTableContest = $('td.navTableContest');

    // WRAP A SPAN ARROUND THE NAVIGATION BUTTON.
    if (elBtnRed1.length) {
        elBtnRed1.wrap('<span class="btnRed1" />');
    }
    if (elBtnBordeaux.length) {
        elBtnBordeaux.wrap('<span class="btnBordeaux" />');
    }
    if (elBtnWhite1.length) {
        elBtnWhite1.wrap('<span class="btnWhite1" />');
    }

    /* THIS DETECTS THE NUMBER OF TDS, EACH TD = BUTTON,
    TO PLACE ALIGN LEFT WHEN THERE ARE 2 BUTTONS */
    if (elNavTableContest.length) {
        var iNumberTd = elNavTableContest.find('td').length;
        if (iNumberTd > 1) {
            elNavTableContest.addClass('navTwoButtons');
        }
    }
}

/* SB.UI.fnUserContest
* FUNCTION TO BE CALLED BY SERVER SIDE, AJAX UPDATE PANEL, CINEMA CONTEST USER CONTROL.
*
*/
SB.UI.fnUserContest = function () {
    SB.UI.initWrapButton();
    SB.UI.initLabelDefaultValue('.lineTextarea textarea');
    SB.UI.contestNonLogged();
}

/* SB.UI.cinemaResultsPagination
* THIS FUNCTION INITS PAGINATION FOR RESULTS LIST CINEMA TYPE LOCALIDADE.
*
*/
SB.UI.cinemaResultsPagination = function () {
    var iItemsPerPage = 10;
    var iTotalItems = $('.moduleSearch > div').length;

    if (iTotalItems > iItemsPerPage) {
        $('div#pagerStyle9').aqPaging(
			{
			    current: 1,
			    pages: 60,
			    pagerMax: 3,
			    flip: true,
			    style: 2,
			    itemsPerPage: 10,
			    objToPaginate: $('.moduleSearch'),
			    // CALLBACK FUNCTION TO RESET HEIGHTS
			    cb: function ($p) {

			        var curr = $p;
			        if (curr == 1) {
			            SB.UI.EqualHeight($(".colum"));
			        }

			    }
			}
		);
    }
}

/* SB.UI.initTabPagination
* THIS FUNCTION INITIALIZES THE PAGINATION OF THE TABS IN WINNERS TAB FOR CONTEST CINEMA AND MUSIC
*
*/
SB.UI.initTabPagination = function () {

    var elPaginationResults = $('div.tabPaginationResults'),
		iItemsPerPage = 3;

    elPaginationResults.each(function () {

        var elThis = $(this),
			sElThisId = elThis.attr('id'),
			iTotalItems = elThis.find('ul').length,
			elPager = elThis.parent().find('.tabPaginationPager'),
			sElPagerId = elPager.attr('id');

        if (iTotalItems > iItemsPerPage) {
            $('#' + sElPagerId).aqPaging(
				{
				    current: 1,
				    pages: 60,
				    pagerMax: 3,
				    flip: true,
				    style: 2,
				    itemsPerPage: iItemsPerPage,
				    objToPaginate: $('#' + sElThisId)
				}
			);
        }
    });
}

/* SB.UI.initMovieComment
* THIS FUNCTION INITIALIZES THE PAGINATION OF THE TABS IN WINNERS TAB FOR CONTEST CINEMA AND MUSIC
*
* Params: [DOM Element] param - string to know if the page make "reload"
*
*/
SB.UI.initMovieComment = function (param) {
    SB.UI.initLabelDefaultValue('.addComment input[type=text], .addComment textarea');

    if (param == 'reload') {

        var elCommentCinema = $('div.commentCinemaWrap'),
			oCinemaOffset = elCommentCinema.offset(),
			oCinemaOffsetTop = Number(oCinemaOffset.top) - 65;

        $('html, body').animate({ scrollTop: oCinemaOffsetTop }, 50);
    }
}

/* SB.UI.CustomPartnersRadio
* THIS FUNCTION CUSTOMIZE THE RADIO BUTTON ON CINEMA PARTNERS
*
*/
SB.UI.CustomPartnersRadio = function () {
    var elInRadio = $('.participateMovie .containerQuestions');
    var elLiCustom = elInRadio.find('input');
    elLiCustom.addClass('styled');
}

/* SB.UI.GlobalCounter
* METHOD TO TRACK COUNTERS.
*
* Params: [DOM Element] el - string that is clicked by the user
* Params: [DOM Element] msg - string to call the service
SB.UI.GlobalCounter('.linkLogin', 'loginbutton');
SB.UI.GlobalCounter('#outro-link-com-id', 'loginbutton');
*/
SB.UI.GlobalCounter = function (el, msg) {
    $(el).click(
        function (e) {
            $.ajax(
                {
                    type: "GET",
                    url: "/base/services/setGlobalCounter/" + msg,
                    contentType: "application/json; charset=utf-8",
                    success:
				        function (data, textStatus, xhr) {
				            // Nothing to do
				        },
                    error:
				        function (jqXHR, textStatus, errorThrown) {
				            // nothing to do
				        }
                }
            );
        }
    )
}

/* SB.UI.GlobalCounterMessage
* METHOD THAT RETURN THA MESSAGE OF GLOBAL COUNTER
*
* Params: [DOM Element] msg - string to call the service
*/
SB.UI.GlobalCounterMessage = function (msg) {
    $.ajax({
        type: "GET",
        url: "/base/services/setGlobalCounter/" + msg,
        contentType: "application/json; charset=utf-8",
        success:
		function (data, textStatus, xhr) {
		    // Nothing to do
		},
        error:
		function (jqXHR, textStatus, errorThrown) {
		    // nothing to do
		}
    })
}


/* SB.UI.initSlideFade
* init the slideshow with fade moviment
*
*/
SB.UI.initSlideFade = function () {
    var wowSlider = new WowSlider(
	    {
	        effect: "fade",
	        prev: "",
	        next: "",
	        duration: 10 * 350,
	        delay: 20 * 100,
	        outWidth: 304,
	        outHeight: 408,
	        width: 304,
	        height: 408,
	        caption: false,
	        controls: false,
	        //autoPlay: true,
	        autoPlay: false,
	        //bullets: true
            bullets:false
	        
	    }
    );
}

/* SB.UI.initSlideWithNavigation
* init the slideshow with fade moviment and with bullet navigation
*
*/
SB.UI.initSlideWithNavigation = function () {
    $('#supersize').supersized();

    numberImage = $('#supersize').length;

    if (numberImage == 1) {
        $.fn.supersized.options = {
            startwidth: 720,
            startheight: 299,
            vertical_center: 1,
            slideshow: 1,
            navigation: 1,
            transition: 0, //0-None, 1-Fade, 2-slide top, 3-slide right, 4-slide bottom, 5-slide left
            pause_hover: 0,
            slide_counter: 1,
            slide_captions: 1,
            slide_interval: 4000
        };
    } else {
        $.fn.supersized.options = {
            startwidth: 720,
            startheight: 299,
            vertical_center: 1,
            slideshow: 1,
            navigation: 1,
            transition: 1, //0-None, 1-Fade, 2-slide top, 3-slide right, 4-slide bottom, 5-slide left
            pause_hover: 0,
            slide_counter: 1,
            slide_captions: 1,
            slide_interval: 4000
        };
    }
}

/* SB.UI.initPaginationCommentList
* init the PAGINATOR on comments list
*
*/
SB.UI.initPaginatorCommentList = function () {

    var iComments = $('.commentWrap').children().length;
    var iCommentsPerPage = 2;

    if (iComments > iCommentsPerPage) {
        $('div.commentCinemaWrap div#pagerStyle8').aqPaging({
            current: 1,
            pages: 60,
            pagerMax: 3,
            flip: true,
            style: 2,
            itemsPerPage: iCommentsPerPage,
            objToPaginate: $('.commentWrap')
        });
    }
}

/* SB.UI.initCustomInputFile
* init customization of input file
*
*/
SB.UI.initCustomInputFile = function () {
    $('input[type=file]').bind("change", function () {
        filename = $('input[class=file]');
        valueInputFile = $('input[type=file]').val();

        if ($.browser.safari || $.browser.chrome) {
            valueInputFileSplit = valueInputFile.split('fakepath');
            elValue = valueInputFileSplit[1].substring(1);

            filename.val(elValue);
        } else {
            filename.val(valueInputFile);
        }
    });
}

/* SB.UI.initSercultur
* init sercultur data cinema
*
*/
SB.UI.initSercultur = function () {
    var elMovieWrapper = $('div.sidebarSearchMovie div.dropdownSearchWrap'),
            iWrapperHeight = elMovieWrapper.height(),
            sLoading = '<div class="loading">&nbsp;</div>';

    $("div.sidebarSearchMovie").delegate(".field", "click", function () {

        var lenghtDistrict = ($("select#location").find('option').length),
        lenghtMovieTheaters = ($("select#movieTheaters").find('option').length),
        lenghtMovie = ($("select#movie").find('option').length),
        lengthType = ($("select#type").find('option').length),
        lengthDistrict = ($("select#district").find('option').length),
        lengthPrice = ($("select#price").find('option').length);

        if ((lenghtDistrict == 1) || (lenghtMovieTheaters == 1) || (lenghtMovie == 1) || (lengthType == 1) || (lengthDistrict == 1) || (lengthPrice == 1)) {

            elMovieWrapper.css('opacity', '0.5');

            $(this).find('.wait').html(sLoading);

            SB.SERCULTUR.GetDistricFromSercultur('', '', '');
            SB.SERCULTUR.GetMovieTheatersFromSercultur('', '', '');
            SB.SERCULTUR.GetMoviesFromSercultur('', '', '');
            SB.GOOUT.GetTypeFromGoOut();
            SB.GOOUT.GetLocalFromGoOut();
            SB.GOOUT.GetPriceFromGoOut();
        }

    })

    $("div.sidebarSearchMovie .field:eq(0)").trigger('click');


    $("select#location").change(function () {
        selectLocation = ($("select#location option:selected").val())

        selectMovie = ($("select#movie option:selected").val())
        selectMovieTheather = ($("select#movieTheaters option:selected").val())

        if (selectLocation == 0) {
            SB.SERCULTUR.GetDistricFromSercultur('', '', '');
            SB.SERCULTUR.GetMoviesFromSercultur('', '', '');
            SB.SERCULTUR.GetMovieTheatersFromSercultur('', '', '');
        } else {
            SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, '', '');
            SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, '', '');
        }

        if (selectMovieTheather == 0 && selectMovie != 0) {
            SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, selectMovie, '');
            SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, selectMovie, '');
        } else {
            if (selectMovieTheather != 0 && selectMovie == 0) {
                SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, '', selectMovieTheather);
                SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, '', selectMovieTheather);
            } else {
                if (selectMovieTheather != 0 && selectMovie != 0) {
                    SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                    SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                }

            }

        }

        SB.SERCULTUR.ValidateForm();
    });


    $("select#movieTheaters").change(function () {
        selectMovieTheather = ($("select#movieTheaters option:selected").val());

        selectMovie = ($("select#movie option:selected").val());
        selectLocation = ($("select#location option:selected").val())

        if (selectMovieTheather == 0) {
            SB.SERCULTUR.GetMovieTheatersFromSercultur('', '', '');
            SB.SERCULTUR.GetMoviesFromSercultur('', '', '');
            SB.SERCULTUR.GetDistricFromSercultur('', '', '');
        } else {
            SB.SERCULTUR.GetDistricFromSercultur('', '', selectMovieTheather);
            SB.SERCULTUR.GetMoviesFromSercultur('', '', selectMovieTheather);
        }

        if (selectLocation == 0 && selectMovie != 0) {
            SB.SERCULTUR.GetDistricFromSercultur('', selectMovie, selectMovieTheather);
            SB.SERCULTUR.GetMoviesFromSercultur('', selectMovie, selectMovieTheather);
        } else {
            if (selectLocation != 0 && selectMovie == 0) {
                SB.SERCULTUR.GetDistricFromSercultur(selectLocation, '', selectMovieTheather);
                SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, '', selectMovieTheather);
            } else {
                if (selectLocation != 0 && selectMovie != 0) {
                    SB.SERCULTUR.GetDistricFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                    SB.SERCULTUR.GetMoviesFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                }

            }
        }

        SB.SERCULTUR.ValidateForm();
    })


    $("select#movie").change(function () {

        selectMovie = ($("select#movie option:selected").val());

        selectMovieTheather = ($("select#movieTheaters option:selected").val());
        selectLocation = ($("select#location option:selected").val())

        if (selectMovie == 0) {
            SB.SERCULTUR.GetMoviesFromSercultur('', '', '');
            SB.SERCULTUR.GetDistricFromSercultur('', '', '');
            SB.SERCULTUR.GetMovieTheatersFromSercultur('', '', '');
        } else {
            SB.SERCULTUR.GetMovieTheatersFromSercultur('', selectMovie, '');
            SB.SERCULTUR.GetDistricFromSercultur('', selectMovie, '');

        }
        if (selectMovieTheather == 0 && selectLocation != 0) {
            SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, selectMovie, '');
            SB.SERCULTUR.GetDistricFromSercultur(selectLocation, selectMovie, '');
        } else {
            if (selectMovieTheather != 0 && selectLocation == 0) {
                SB.SERCULTUR.GetMovieTheatersFromSercultur('', selectMovie, selectMovieTheather);
                SB.SERCULTUR.GetDistricFromSercultur('', selectMovie, selectMovieTheather);
            } else {
                if (selectMovieTheather != 0 && selectLocation != 0) {
                    SB.SERCULTUR.GetMovieTheatersFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                    SB.SERCULTUR.GetDistricFromSercultur(selectLocation, selectMovie, selectMovieTheather);
                }

            }
        }

        SB.SERCULTUR.ValidateForm();
    });

}

SB.UI.checkAgeControls = function () {
    var today = new Date(),
        ageLimitSelectedCountry = $('#country').val(),
        day = $('#day').val(),
        month = $('#month').val(),
        year = $('#year').val(),
        yearLength = year.length,
        elError = $('.msgErrorLanding');

    if (day == "" || month == "" || year == "") {
        elError.html('Tens que inserir a tua data de nascimento. <span>Please insert your date of birth.</span>');
        //alert("Tens de inserir a tua data de nascimento.");
        return false;
    }

    if ((month < 1 || month > 12) || (day < 1 || day > 31) || (year < 1900 || year > 2012) || (yearLength < 4)) {
        elError.html('A data de nascimento que inseriste não é válida. <span>Please insert a valid and full date of birth.</span>');
        //alert("A data de nascimento que inseriste não é válida.");
        return false;
    }

    else {
        var userAge = today.getFullYear() - year;

        if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) { userAge--; }

        if (userAge >= ageLimitSelectedCountry) {

            return true;
        }
        else {
            elError.html('Não tens a idade mínima legal para entrar no site. <span>You must be of legal drinking age to enter this site. </span>')
           // alert("Não tens idade mínima legal para entrar no site.");
            return false;
        }
    }
}


