// All jQuery functions on page load
$(document).ready(function () {

    //-----------------------------START - FORGOT PW MODAL --------------------------//
    $('#forgotPWDiv').jqm({ modal: true, trigger: '#btn-forgot_password' });
    //-----------------------------END - FORGOT PW MODAL ----------------------------//

    // Signup Success modal
    $('#signupSuccess').jqm({ modal: true, overlay: 0 }).jqmShow();

    // CUFON FONT REPLACEMENT
    Cufon.replace('h2');
    Cufon.replace('h3');
    if ($('#header-dont_have').is(':visible')) Cufon.replace('#header-dont_have');
    if ($('#bg-header-account').is(':visible')) Cufon.replace('#bg-header-account');
    if ($('#home_callout strong').is(':visible')) Cufon.replace('#home_callout strong');
    if ($('#account_welcome').is(':visible')) Cufon.replace('#account_welcome');
    if ($('#activity_tabs li strong').is(':visible')) Cufon.replace('#activity_tabs li strong');
    if ($('.btn-green').is(':visible')) Cufon.replace('.btn-green');
    if ($('.btn-orange').is(':visible')) Cufon.replace('.btn-orange');
    if ($('.special_radio span').is(':visible')) Cufon.replace('.special_radio span');
    if ($('#breadcrumb li').is(':visible')) Cufon.replace('#breadcrumb li');
    if ($('.review_info h4').is(':visible')) Cufon.replace('.review_info h4');
    if ($('.emphasis').is(':visible')) Cufon.replace('.emphasis');
    if ($('.btn-close_modal').is(':visible')) Cufon.replace('.btn-close_modal');
    if ($('#navigation a').is(':visible')) {
        Cufon.replace('#navigation a');
        $('#navigation a').hover(function () {
            Cufon.refresh('#navigation a');
        }, function () {
            setTimeout(function () { Cufon.refresh('#navigation a'); }, 25);
        });
    };

    // In Field Labels
    $("label").inFieldLabels(); // REMEMBER: for in-field labels to work, every label with corresponding input/textarea needs to have the same unique ID, FOR, and NAME

    // click event to toggle login modal
    $('#btn-login').click(function () {
        $('#login').slideToggle(350);
        return false;
    });

    // Scroll Follow
    $('#navigation').scrollFollow({
        container: 'wrapper',
        offset: 0
    });

    // click event to toggle between tabs
    $('#activity_tabs li').click(function () {
        var curChildIndex = $(this).prevAll().length + 1;
        $(this).parent().children('.current').removeClass('current');
        $(this).addClass('current');
        Cufon.refresh('#activity_tabs li strong');
        if ($(this).parent().next('#tab_holders').is(':visible')) {
            $(this).parent().next('#tab_holders').children('.show').slideUp(350, function () {
                $(this).removeClass('show');
                $('#tab_holders').children('div:nth-child(' + curChildIndex + ')').slideDown(350, function () {
                    $(this).addClass('show');
                });
            });
        } else {
            $(this).parent().parent().next('#tab_holders').children('.show').slideUp(350, function () {
                $('#filter_discussion').slideToggle('fast');
                $(this).removeClass('show');
                $('#tab_holders').children('div:nth-child(' + curChildIndex + ')').slideDown(350, function () {
                    $(this).addClass('show');
                });
            });
        }
        return false;
    });

    // click events to trigger actions for the goals in sidebar
    $('#profile-bio .btn-edit-profile').click(function () {
        $('.edit_profile').delay(350).slideDown();
    });
    $('.btn-edit').click(function () {
        if ($(this).parent().hasClass('note_actions')) {
            $(this).parent().parent().find('.note_view').slideUp(350, function () {
                $(this).parent().find('.note_edit').slideDown(350);
            });
        } else {
            $(this).parent().slideUp(250, function () {
                if ($(this).parent().find('.edit_goal').is(':hidden')) {
                    $(this).parent().find('.edit_goal').slideDown();
                }
            });
        };
        return false;
    });
    $('#btn-add-goal').click(function () {
        $('#add_goal').slideDown();
        return false;
    });

    $('.edit_goal textarea').keypress(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            if ($(this).parent().parent().parent().find('.name_goal').is(':hidden')) {
                $(this).parent().parent().slideUp(350, function () {
                    $(this).parent().find('.name_goal').slideDown(350);
                });
            } else if ($(this).parent().parent().parent().attr('id') == 'add_goal') {
                $(this).parent().parent().parent().slideUp();
            };
            //            if (event && event.preventDefault) {
            //                event.preventDefault();
            //            }
        };
    });

    $('.goal_title').click(function () {
        $(this).parent().find('.goal_description').slideDown(350);
        return false;
    });

    /* click button to close edit profile textarea and show updated profile bio */
    $('#btn-submit-edit_profile').click(function () {
        $(this).parent().parent().slideUp(250, function () {
            $('#profile-bio').slideDown();
        });
        //        if ( event && event.preventDefault) {
        //            event.preventDefault();
        //        }
    });

    // -------------------------------------------------click event triggers dropdown
    $('.dropdown').click(function () {
        $(this).find('.dropdown_list').slideToggle();
    });

    $('.dropdown_list li').click(function () {
        var thisOption = $(this).text();
        var dropdown = $(this).parent().parent();
        $(dropdown).find('.dropdown_name').html(thisOption);
        if (dropdown.attr('id') == 'categoryDropdown') {
            $('#subitemDropdown').find('.dropdown_name').html('Select');
            GetSubItemList(thisOption);
        }

    });
    //keypress event triggered when editing a note in the Notes page(s)
    $('.note_edit textarea').keypress(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            if ($(this).parent().parent().parent().find('.note_view').is(':hidden')) {
                $(this).parent().parent().slideUp(350, function () {
                    $(this).parent().find('.note_view').slideDown(350);
                });
            }

            //            if ( event && event.preventDefault) {
            //                event.preventDefault();
            //            }
        };
    });

    $('.modal_bg').click(function () {
        $('.btn-close_modal').trigger('click');
        $('.jqmOverlay').fadeOut(250);
    });

    $('.btn-close_modal').click(function () {
        $('.modal').fadeOut();
        return false;
    });

    $('.btn-close_modal-top').click(function () {
        $('.btn-close_modal').trigger('click');
    });

    //-----------------------------START - UPLOAD PROFILE PHOTO ---------------------//

    $('#photoUpload input[type=file]').bind('change', function () {
        $('#photoUpload input[type=submit]').trigger('click');
    });

    function updateProfile() {
        var profileID = parseInt($('#describe_profile_input').attr("profileID"));
        var Object = $('#describe_profile_input');
        UpdateBio(profileID, $(Object).val());

    }

    $('#btn-submit-edit_profile').click(function () {
        $(this).parent().parent().slideUp(250, function () {
            $('#profile-bio').slideDown();
        });
        updateProfile();
        return false;
    });

    //-----------------------------END - UPLOAD PROFILE PHOTO -----------------------//

    //-------------------------------------------START - LOGIN ENTER -------------------------------//
    $('#LoginNameCtrl').keypress(function(event){
        LoginKeyPress(event);
    });

    $('#LoginPasswordCtrl').keypress(function (event) {
        LoginKeyPress(event);
    });

    function LoginKeyPress(event)
    {
        var keycode = (event.keyCode ? event.keyCode : event.which);

        if (keycode == '13') {
            $('#LoginBtnCtrl').trigger('click');
            event.preventDefault();
        }
    }

    $('#LoginBtnCtrl').click(function (event) {
        var pw = $('#LoginPasswordCtrl').val();
        var user = $('#LoginNameCtrl').val();
        Login(user, pw);
    });

    //-------------------------------------------END - LOGIN ENTER ---------------------------------//

    //-------------------------------START - DONT BOTHER ME --------------------------------//

    $('#PromoBtn').click(function () {
        var botherMe = $('#botherMeCheckBx')[0].checked;
        document.cookie = 'FarmOn-botherMeAgain=' + botherMe;
        return this;
    });


    //-------------------------------------END - DONT BOTHER ME ------------------------------//

    // Split FAQ list into equal columns
    $('#faq ul').makeacolumnlists({ cols: 2, colWidth: 0, equalHeight: false });

    // Set attributes for Share This icons
    var courseTitle = $.trim($('#course_title h4').text());
    $('#share-this span').attr('st_title', courseTitle);
	
	
	/* START : NEWS CAROUSEL */
	 if($('#news-slider').is(':visible')) {
		 $('#news-slider').anythingSlider({
				width : 522,          // Override the default CSS width
				easing: 'easeInOutExpo',
				autoPlay: true
		});
	 };
	/* END : NEWS CAROUSEL */
	
	$('input').focus(function() {
		$(this).css({
			'border-color' : '#bbb'
		});
	});
	
	$('input').focusout(function() {
		$(this).css({
			'border-color' : '#d1cfc9'
		});
	});
	
});

//-------------------------------START - DONT BOTHER ME --------------------------------//
function BotherMeNotCheck() {
    var cookie = getCookie('FarmOn-botherMeAgain');
    if (cookie == null || cookie == 'true') {
        $('#WelcomeModal').fadeIn();
    }
}
//-------------------------------------END - DONT BOTHER ME ------------------------------//

//---------------------------START - ERROR FLAGGING -------------------------------------------------------//
function ShowLoginErrors(errorMsg) {
    if ($('#login').is(':hidden') == true) {
        $('#btn-login').click();
    }
    $('#responseErrorCtrl').html(errorMsg);
}


function SetErrorFlag(errs) {
    for (index = 0; index < errs.length; index++) {
        $('#' + errs[index]).addClass('error_input');
    }
}
//---------------------------END - ERROR FLAGGING ---------------------------------------------------------//

//-----------------------------START - FB INVITE ---------------------------------------------------------//
function SendFBInvite(fbID, msg) {
    if (FB) {
        var response = FB.ui({
            method: 'apprequests',
            message: msg,
            to: fbID
        });
    }
}

function SendFBMultiInvite(msg) {
    if (FB) {
        var response = FB.ui({
            method: 'apprequests',
            message: msg
        });
    }
}

//---------------------------------END - FB INVITE ---------------------------------------------------------//

//------------------------------------START - GET COOKIE ----------------------//
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}
//------------------------------------END - GET COOKIE -----------------------//


//------------------------- START - AJAX FUNCTIONS---------------------------------------------
function submitAjax(isPost, data, callbackFunc) {
    var SubmitType = isPost ? "POST" : "GET";
    $.ajax({
        type: SubmitType,
        url: "/handlers/AjaxHelper.ashx",
        data: data,
        success: callbackFunc
    });
}


//BEGIN -------------------------------------------- Dropdown Sub Item list
function GetSubItemList(browseOption) {
    var dataObj = JSON.stringify(
                {
                    BrowseOption: browseOption
                });

    submitAjax(false,
                        {
                            action: 'CourseSubItemLookup',
                            data: dataObj
                        }, function (resp) {
                            var dataObj = JSON.parse(resp);

                            var html = "";
                            for (i = 0; i < dataObj.SubItems.length; i++) {
                                html += "<li onclick=\"window.location = '" + dataObj.SubItems[i].Url + "';\">" + dataObj.SubItems[i].Text + "</li>";
                            }

                            $('#subitemDropdown .dropdown_list').html(html);
                        });
}

function GoToUrl(url) {
    window.location = url;
}

//END ---------------------------------------------- Dropdown Sub item list

//---------START - FORGOT PASSWORD --------------------------------------//
function ForgotPassword() {
    var email = $('input#forgotPwEmail').val();
    var dataObj = JSON.stringify(
                                {
                                    UserEmail: email
                                });

    submitAjax(true,
                                {
                                    action: "ForgotPassword",
                                    data: dataObj
                                }, function (response) {
                                    var Response = JSON.parse(response);
                                    $('#forgotPwResponse').html(Response.DisplayText);
                                });

}
//--------END - FORGOT PASSWORD---------------------//


//updateBio
function UpdateBio(userid, bio) {
    var dataObj = JSON.stringify(
                {
                    UserID: userid,
                    Bio: bio
                });
    submitAjax(true,
                {
                    action: "UpdateBio",
                    data: dataObj
                },
                function (response) {
                    window.location.reload();
                });
}


//BEGIN - SOCIAL FOLLOW
function SocialFollowCmd(sender, socialID, TargetType, followText, unFollowText) {
    var Following = $(sender).attr('isfollowing');

    var dataObj = JSON.stringify(
                    {
                        FollowTargetType: TargetType,
                        FollowingSocialID: socialID,
                        Follow: Following
                    });

    submitAjax(true,
                    {
                        action: "SocialFollow",
                        data: dataObj
                    });

    SetFollowText(sender, Following.toLowerCase() == "true" ? false : true, followText, unFollowText);
}

function SetFollowText(sender, isFollowing, followText, unFollowText) {
    $(sender).attr('isfollowing', isFollowing);

    var linkText = "";
    if (isFollowing == true) {
        linkText = unFollowText;
    }
    else {
        linkText = followText;
    }

    $(sender).text(linkText);
}
//END - SOCIAL FOLLOW

//---------------------------------------------------------------START - FaceBook LoginResponse-------------------------------- //
//if (!_FBPermissions)
//    var _FBPermissions = 'email,user_birthday'; //this variable gets set in the site master with the data from the web.config

function FBLogin() {
    /****START - FB CHECK ****/
    if (FB) {
        FB.login(function (response) {
            if (response.authResponse) {
                var dataObj = JSON.stringify(response.authResponse);

                submitAjax(true,{
                                    action: 'FBLogin',
                                    data: dataObj
                                }, function (e) {
                                    var dataObj = JSON.parse(e);
                                    if (dataObj.Status == "success") {
                                        LoginTracking(true);
                                        window.location = dataObj.RedirectUrl;
                                    }
                                    else {
                                        ShowLoginErrors(dataObj.Message);
                                        if (dataObj.RedirectUrl.length > 0) {
                                            window.location = dataObj.RedirectUrl;
                                        }
                                    }

                                });
            }
        },
        { scope: _FBPermissions });
    }
    /*********END - FB CHECK ******/
}



function FBRegister(_isFree) {
    var _isFreeReg = false;
    //set is free first
    if (_isFree != null) {
        _isFreeReg = _isFree;
    }

    /****START - FB CHECK ****/
    if (FB) {

        FB.login(function (response) {
            
            if (response.authResponse) {
                var dataObj = JSON.stringify(response.authResponse);

                submitAjax(true,
                        {
                            action: 'FBRegister',
                            data: dataObj,
                            isFree: _isFreeReg
                        }, function (e) {
                            var dataObj = JSON.parse(e);
                            if (dataObj.Status == "success") {
                                if (dataObj.RedirectUrl.length > 0) {
                                    window.location = dataObj.RedirectUrl;
                                }
                            }
                        });
            }
        },
            { scope: _FBPermissions });


    }
    /*********END - FB CHECK ******/

}


//---------------------------------------------------------------END - FaceBook LoginResponse --------------------------------------//

//----------------------------START - LOGIN TRACKING -----------------------------//
function LoginTracking(isFB, RedirectUrl) {
    if (isFB != null && isFB == true) {
        _gaq.push(['_trackEvent', 'Login', 'FACEBOOK']);
    }
    else {
        _gaq.push(['_trackEvent', 'Login', 'SITE_LOGIN']);
    }

    _gaq.push(function () { window.location = RedirectUrl; });
}
//-------------------------END - LOGIN TRACKING ---------------------------------//

//------------------------------START - COURSE TRACKING --------------------------//
function TrackCourseView(isFree) {
    if (isFree != null && isFree == true) {
        _gaq.push(['_trackEvent', 'Courses', 'Course_View', 'FREE']);
    }
    else {
        _gaq.push(['_trackEvent', 'Courses', 'Course_View', 'PAID']);
    }
}
//------------------------------END - COURSE TRACKING ----------------------------//

//-----------------------------START - LOGIN -------------------------------------//
function Login(username, password) {
    var dataObj = JSON.stringify({
        Username: username,
        Password: password
    });

    submitAjax(true,
                {
                    action: 'Login',
                    data: dataObj
                }, function (e) {
                    var response = JSON.parse(e);
                    if (response.Status == 'Success') {
                        LoginTracking(false, response.RedirectUrl);
                        window.location = response.RedirectUrl;
                    }
                    else {
                        ShowLoginErrors(response.Message);
                    }
                });
}

//-----------------------------END - LOGIN ---------------------------------------//

//-------------------------------------END - AJAX Functions --------------------------------------//

// iframe resizing
//$(document).ready(function(){
//    $(window).bind('hashchange' , function(){
//        var hash = window.location.hash;
//       
//        var id = hash.split('=')[0].replace('#', '');
//        var height = hash.split('=')[1];
//        
//        resizeIframe(id, parseInt(height));
//    });
//});




function resizeIframe(id, height) {
    var frame = $('#' + id);
    frame.css('height', height);
    frame.height(height);
}
function resizeIframe(id, height) {
    var frame = $('#' + id);
    frame.css('height', height);
    frame.height(height);
}

