$(document).ready(function () {

//    if ($('#mainNav li').length > 0) {
//        $('#mainNav ul').has('ul').addClass('sub');
//    }
    //CHECK IF USER IS LOGGED IN. IF YES, CHANGE LOGIN BUTTON
    var sess = window.FCsX.GetSession();
    if (sess) {
        if (window.FCsX.IsInRole("registered")) {
            window.FCsX.GetProfile(function (data, textStatus, jqXHR) {
                var nickname = data.Profile.FirstName;
                str = "<span class='name'> Welcome " + nickname + "</span>";
                 $("#login-box").empty().append("<span id='logout-button'><a id='signOut' href='#'>sign out</a></span>").find("#logout-button").click(function () {
                    logout();
                });
//                $("#login-box").empty().append("<span class='name'> Welcome " + nickname + "</span><span id='logout-button'><a href='#'><img src='" + MLC.GetStorageUrl() + "shared/images/jslogout.gif' alt='Logout' /></a></span>").find("#logout-button").click(function () {
//                    logout();
//                });


            });
        }
    }
    //On Hover Over
    function megaHoverOver() {
        $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
        (function ($) {
            //Function to calculate total width of all ul's
            jQuery.fn.calcSubWidth = function () {
                rowWidth = 0;
                //Calculate row
                $(this).find(".menuContainer > li").each(function () { //for each ul...
                    rowWidth += $(this).outerWidth(true); //Add each ul's width together
                });

                //even out the heights

            };
        })(jQuery);

        if ($(this).find(".row").length > 0) { //If row exists...

            var biggestRow = 0;

            $(this).find(".row").each(function () {	//for each row...
                $(this).calcSubWidth(); //Call function to calculate width of all ul's
                //Find biggest row
                if (rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });

            $(this).find(".sub").css({ 'width': biggestRow }); //Set width
            $(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin

        } else { //If row does not exist...
            var sco = $('.menuContainer', this).length > 0;

            $(this).calcSubWidth();  //Call function to calculate width of all ul's
            if (sco === false) {
                $(this).find(".sub").css({ 'width': rowWidth }); //Set Width
            }
        }
    }
    //On Hover Out
    function megaHoverOut() {
        $(this).find(".sub").stop().fadeTo('fast', 0, function () { //Fade to 0 opactiy
            $(this).hide();  //after fading, hide it
        });
    }

    //Set custom configurations
    var config = {
        sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 200, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $("#mainNav li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
    $("#mainNav li").hoverIntent(config); //Trigger Hover intent with custom configurations


    if ($('#slideshow').length > 0) {
        var slides = $('.slide').length;
        var navmarg = 482 - (16 * slides);
        $('#slideshow').before('<div id="ssnav">').cycle({
            fx: 'fade',
            pager: '#ssnav',
            onPagerEvent: function () { $('#slideshow').cycle('pause'); },
            slideResize: 0
        });
        $('#ssnav').css("marginLeft", navmarg);
    }

    $(".selectbox").selectbox();

    $(".rating").children().not(":radio").hide();
    $(".rating").stars();



});


function handleFBFriends() {

    FB.getLoginStatus(handleFBData);

}
function handleFBData(response) {
 
    if (response.authResponse) {

       // FB.api('/me/friends', { fields: 'name,id,location,birthday' }, function (response) {
        FB.api({
            method: 'fql.query',
            query: 'SELECT uid, first_name, last_name,sex, birthday, birthday_date FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) order by birthday_date'
        }, function (response) {
            
            handleBdays(response);
        });


    }
    else {
        
        if ($('#fbLogin').length) {
            var button = document.getElementById('fbLogin');
            button.value = 'Login';
            button.style.display = '';
            button.onclick = function () {
                FB.login(handleFBData, { scope: 'user_about_me,user_interests,user_location,email,read_friendlists,publish_stream,manage_pages,user_groups,user_events,user_checkins,user_likes' });
            }
        }

    }
}



function handleBdays(results) {

    results = jQuery.grep(results, function (n, i) {
        var today = new Date();
        var currentMonth = today.getMonth() + 1;
        var currentDay = today.getDay

        if (n.birthday != undefined) {
            if (currentMonth == n.birthday_date.substr(0, 2) * 1) {
                return (n.birthday != undefined && currentDay <= n.birthday_date.split("/",2)[1] * 1);
            } else {
                return (n.birthday != undefined && currentMonth < (n.birthday_date.substr(0, 2) * 1));
            }
            
        } else {
            return (n.birthday != undefined);
        }
    });
  
  

        // Build a row of data for each product

        

        var x;

        var html = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"fbFriends\">";
        for (x = 0; x < 6; x++) {
           
            
            if (x == 0 || x == 2 || x==4) {
                html += '<tr>';
            }
            html += '<td  style="width:50px; padding-top:10px;"><img src="https://graph.facebook.com/' + results[x].uid + '/picture"></div>';
            html += '<td style="padding-left:10px; padding-top:10px;width:150px; vertical-align:top;" ><div ><strong>' + results[x].birthday.split(",", 1)[0] + '</strong></div><div >' + results[x].first_name + '</div>';
            var url;
            if (results[x].sex == 'male') {
                url = "/gifts/birthday-for-him";
            } else if (results[x].sex == 'female') {
                url = "/gifts/birthday-for-her";
            } else {
                url = "/";
            }
            html += '<div><a style="color:#EB1C2C; font-weight:bold;" href="' + url + '">Find Gifts</a><div>';
            html +='</td>';
            if (x == 1 || x == 3 || x == 6) {
                html += '</tr>';
            }


        }
        html += "</table>";


        $('#fbFriends').html(html);
        $('#fbFriends').show();

   

}
