﻿var myLivenation = {};

$(function() { myLivenation.init(); });

(function() {
    myLivenation = {
        facebook: {
            apiKey: "",
            xdPath: "",
            thumbPath: "http://static.ak.fbcdn.net/pics/t_silhouette.jpg",
            init: function() {
                myLivenation.facebook.loginShowHidePassword();
                $('input[type=radio].switch').click(function() {
                    myLivenation.facebook.loginShowHidePassword();
                });
                $(".fb-fill-form").click(function() {
                    myLivenation.facebook.fillForm();
                });
                $('.fb-unlink').click(function() {
                    myLivenation.facebook.unlinkAccount();
                    return false;
                });
                $('#fb-disconnect').click(function() {
                    ShowFacebookDisconnectPopup("Facebook Connect");
                    return false;
                });
            },
            loginShowHidePassword: function() {
                if ($('input[name=IsAccountHolder]:checked').val() == "True") {
                    $('#ConnectExisting').show();
                    $('#ExtraDetails').hide();
                } else {
                    $('#ConnectExisting').hide();
                    $('#ExtraDetails').show();
                }
            },
            doLogout: function() {
                FB.Connect.logout(function() {
                    window.location.href = "/account/signout";
                });
            },
            unlinkAccount: function() {
                FB.Facebook.apiClient.revokeAuthorization(FB.Connect.get_loggedInUser(), function() { window.location.href = "/myln" });
            },
            fillForm: function() {
                $('.fb-text').each(function() {
                    var id = myLivenation.facebook.stripPrefix($(this).attr('id'));
                    $('#' + id).val($(this).html());
                    $('#' + id).addClass("autofill");
                });
                if ($('#FacebookGender').val() == "Male") {
                    $('input[name="Gender"]')[0].checked = true;
                    $('#GenderWrap').addClass("autofill");
                }
                if ($('#FacebookGender').val() == "Female") {
                    $('input[name="Gender"]')[1].checked = true;
                    $('#GenderWrap').addClass("autofill");
                }
                if ($('#FacebookLocaleName').val() != "") {
                    $('#PreferredCulture').val($('#FacebookLocaleName').val());
                    $('#PreferredCulture').addClass("autofill");
                }
                if ($("#BirthDay").length > 0) {
                    $('#Day').val($('#BirthDay').val());
                    $('#Day').addClass("autofill");
                }
                if ($("#BirthYear").length > 0) {
                    $('#Month').val($('#BirthMonth').val());
                    $('#Month').addClass("autofill");
                }
                if ($("#BirthYear").length > 0) {
                    if ($("#BirthYear").val() != $('#Year').val()) {
                        $('#Year').val($('#BirthYear').val());
                        $('#Year').addClass("autofill");
                    }
                }

            },
            stripPrefix: function(id) {
                return id.replace('fb-', '');
            },
            askForExtendedPermissions: function() {
                FB.Connect.showPermissionDialog("publish_stream,offline_access", function(perms) {

                    window.location.href = "/account/connect";
                    //if (!perms) {
                    //  alert("You cannot Connect via Facebook without allowing the requested permissions");
                    //} else {
                    //  window.location.href = "/Account/Connect";
                    //}
                });
            },
            connectToExistingMember: function() {
                FB.Connect.showPermissionDialog("publish_stream,offline_access", function(perms) {
                    $.getJSON('/Account/ConnectExisting', function(results) {
                        switch (results.response) {
                            case 1:
                                window.location.href = "/account/edit";
                                break;
                            case 3:
                                alert("TODO: account already exist copy goes here");
                                break;
                            default:
                                window.location.href = "/account/edit";
                        }
                    });
                });
            }
        },
        init: function() {
            this.favorites.init();
        },
        favorites: {
            init: function() {
                ln.utility.popuptitle();
                $('#faveButton').click(function() {
                    $('.popuptitle .jsPopupBox').css('opacity', 0);
                    var contentType = $(this).parent().parent().find('#ContentType').val();
                    var contentId = $(this).parent().parent().find('#ContentID').val();
                    $('#faveButton').hide();
                    $.getJSON('/MyLN/AddToFavourite/' + contentType + "/" + contentId + '?' + Math.random(), function(results) {
                        switch (results.response) {
                            case 3:
                                $('#faveButton').show();
                                var title = $('#alertHeaderTitle').val();
                                ShowErrorPopup(title);
                                break;
                            case 4:
                                var pathname = window.location.pathname;
                                var location = window.location.href;
                                window.location = location.replace(pathname, "/Account/LoginOrRegister?ReturnUrl=" + pathname);
                                break;
                            default:
                                changeAddFavoriteButton('favorite');
                                var thickboxHeaderTitle = $('#thickboxHeaderTitle').val();
                                ShowAlertPopup(thickboxHeaderTitle);
                        }
                    });
                });
            }
        },
        subscriptions: {
            formSubmitted: false,
            setDefaults: function() {
                this.tabs = $('.subscriptionsForm #tabList li');
                this.divs = $('.subscriptionsForm .content .tabContent');
                this.checkboxs = $(".subscriptionsForm .content .cbSub");
                this.mapListEuropeItems = $('.subscriptionsForm #lnMap li.europe_item');
                this.mapListAsiaItems = $('.subscriptionsForm #lnMap li.asia_item');
                this.mapDiv = $('.subscriptionsForm #lnMap');

                this.mapDiv.addClass('europe');
                this.mapListEuropeItems.show();
                this.divs.eq(0).show();
                this.tabs.eq(0).toggleClass('selected');

                var subscriptionObj = this;
                this.divs.each(function(i, domElement) {
                    var element = $(domElement);
                    var id = $(domElement).attr('id').split("_")[1];
                    element.find('.cbSub').data("communityid", id);

                    element.find(".allSelect").click(function(e) {
                        var checkBoxes = element.find("input:checkbox");
                        checkBoxes.attr('checked', true);
                        subscriptionObj.checkAllForCommunity(id);
                        e.preventDefault();
                    });

                    element.find(".allClear").click(function(e) {
                        var checkBoxes = element.find("input:checkbox");
                        checkBoxes.attr('checked', false);
                        subscriptionObj.unCheckAllForCommunity(id);
                        e.preventDefault();
                    });
                });

                var divs = this.divs;
                this.tabs.each(function(i, domElement) {
                    var element = $(domElement);
                    var communityId = element.attr('id').split("_")[1];
                    var count = $('#tabContent_' + communityId + ' input:checked').size();
                    element.data("text", element.text());
                    element.data("count", count);
                    element.data("defaultCount", count);
                });
            },
            checkAllForCommunity: function(communityId) {
                var id = '#tab_' + communityId;
                var count = $('#tabContent_' + communityId + ' input:checked').size();
                var tab = $(id);
                this.setCountToTab(tab, count);
            },
            unCheckAllForCommunity: function(communityId) {
                var id = '#tab_' + communityId;
                var tab = $(id);
                this.setCountToTab(tab, 0);
            },
            unCheckAll: function() {
                var that = this;
                this.tabs.each(function(i, domElement) {
                    var element = $(domElement);
                    var communityId = element.attr('id').split("_")[1];
                    var checkBoxes = $(".subscriptionsForm input:checkbox");
                    checkBoxes.attr('checked', false);
                    that.unCheckAllForCommunity(communityId);
                });
            },
            onCheckboxChanged: function(checkbox) {
                var communityId = checkbox.data("communityid");
                var id = '#tab_' + communityId;
                var tab = $(id);
                if (checkbox.is(':checked')) {
                    this.addCountToTab(tab);
                } else {
                    this.removeCountFromTab(tab);
                }
            },
            load: function() {
                this.setDefaults();
                var subscriptionObj = this;

                /*
                Check done on submit
                    
                $('.subscriptionsForm input.unsubscribe').click(function() {
                if (($(this).is(':checked'))) {
                subscriptionObj.unCheckAll();
                }
                });
                */

                $('form.subscriptionsForm').submit(function() {
                    if (($('.subscriptionsForm input.unsubscribe').is(':checked'))) {
                        subscriptionObj.unCheckAll();
                    }
                });

                this.tabs.each(function(i, domElement) {
                    var tab = $(domElement);
                    subscriptionObj.setTabText(tab, tab.data("count"));
                });

                $('#btnCancel').click(function() {
                    $('.subscriptionsForm #tabList li').each(function(i, domElement) {
                        var tab = $(domElement);
                        subscriptionObj.setTabText(tab, tab.data("defaultCount"));
                    });
                });

                this.checkboxs.click(function(e) {
                    var checkbox = $(e.target);
                    subscriptionObj.onCheckboxChanged(checkbox);
                });

                $('.subscriptionsForm #switch_europe').click(function(e) {
                    subscriptionObj.mapDiv.addClass('europe');
                    subscriptionObj.mapDiv.removeClass('asia');
                    subscriptionObj.mapListEuropeItems.show();
                    subscriptionObj.mapListAsiaItems.hide();
                    e.preventDefault();
                });

                $('.subscriptionsForm #switch_asia').click(function(e) {
                    subscriptionObj.mapDiv.addClass('asia');
                    subscriptionObj.mapDiv.removeClass('europe');
                    subscriptionObj.mapListEuropeItems.hide();
                    subscriptionObj.mapListAsiaItems.show();
                    e.preventDefault();
                });

                var clickEventForMapItem = function(e) {
                    var map = $(this);
                    var communityId = map.attr('id').split("_")[1];
                    mapLink = $('.subscriptionsForm #tabList #tab_' + communityId);
                    mapLink.click();
                    e.preventDefault();
                };

                subscriptionObj.mapListEuropeItems.click(clickEventForMapItem);
                subscriptionObj.mapListAsiaItems.click(clickEventForMapItem);

                subscriptionObj.divs.filter("#tabContent_0").find("input:checkbox").click(function(e) {
                    var mycheckbox = $(e.target);
                    var isChecked = mycheckbox.attr('checked');
                    var id = mycheckbox.attr('id').split("_")[1];
                    var communityCheckbox = subscriptionObj.divs.find(".subscription_" + id)
                    communityCheckbox.attr('checked', isChecked);
                    subscriptionObj.onCheckboxChanged(communityCheckbox);
                });

                subscriptionObj.tabs.click(function(e) {
                    var tab = $(this);
                    subscriptionObj.unSelectAllTabs();
                    tab.toggleClass('selected');
                    var communityId = tab.attr('id').split("_")[1];
                    subscriptionObj.divs.hide();
                    var tabContentId = '#tabContent_' + communityId;
                    $(tabContentId).show();
                    e.preventDefault();
                });


                //subscription clicked, search for duplicates - update tab counter and tooltip
                $('.cbSub').click(function() {
                    showInfo();
                });
                //select all within a tab
                $(".allSelect").click(function() {
                    showInfo();
                });
                //clear all within a tab
                $(".allClear").click(function() {
                    showInfo();
                });
                //clear all in all tabs
                $(".unsubscribe").click(function() {
                    showInfo();
                });
                //show tab when map clicked
                $('.mapLink').click(function() {
                    showTab($(this).parents('li').attr('id'));
                });
                //tab clicked - show related content and hide others
                $(".tab").click(function() {
                    showTab($(this).attr('id'));
                });
            },
            removeCountFromTab: function(tab) {
                tab.data("count", tab.data("count") - 1);
                this.setTabText(tab, tab.data("count"));
            },
            addCountToTab: function(tab) {
                tab.data("count", tab.data("count") + 1);
                this.setTabText(tab, tab.data("count"));
            },
            setCountToTab: function(tab, count) {
                tab.data("count", count);
                this.setTabText(tab, tab.data("count"));
            },
            setTabText: function(tab, count) {
                if (count > 0) {
                    tab.find(".m").html(tab.data("text") + " <strong><span>(" + count + ")</span></strong>");
                } else {
                    tab.find(".m").html(tab.data("text"));
                }
            },
            unSelectAllTabs: function() {
                this.tabs.removeClass('selected');
            }
        }
    }
})();

//shows the 'save info' box
function showInfo() {
    $('input#btnUpdate').removeAttr("disabled");
    $('input#btnCancel').removeAttr("disabled");
    $('.saveInfo').show();
    return false;
}
function showTab(id) {
    $('.tabContent').hide();
    $('.tab').removeClass('selected');
    $('.mapLink').removeClass('selected');
    var mid = getID(id);
    $('#tabContent_' + mid).show();
    $('#tab_' + mid).addClass('selected');
    $('#map_' + mid + ' a').addClass('selected');
    //HACK: 
    //major hack alert, either need to move these into web.config or change sentinel to identify communities as 'asia/europe'
    if ((mid == "8f1cfc20-5b3b-41f8-a188-0111414c9006") || (mid == "21255103-8ec3-4782-b1d3-5614615897eb") || (mid == "3b278777-ac2e-4aa2-8e89-9fd2c531a7b1")) {
        switchToAsia();
    }
    else {
        switchToEurope();
    }
}
function getID(idIn) {
    try {
        var idArr = idIn.split('_');
        var id = idArr[1];
        return id;
    }
    catch (err) {
        return 0;
    }
}
function switchToEurope() {
    $('#lnMap').removeClass('asia');
    $('#lnMap').addClass('europe');
    $('.europe_item').show();
    $('.asia_item').hide();
}
function switchToAsia() {
    $('#lnMap').removeClass('europe');
    $('#lnMap').addClass('asia');
    $('.europe_item').hide();
    $('.asia_item').show();
   }


function hasFavourite(contentType, contentId) {
	$.getJSON('/MyLN/GetFavouriteStatus/' + contentType + "/" + contentId + '?' + Math.random(), function(results) {
	switch (results.response) {
			case 1: //favourite added
				changeAddFavoriteButton();
				var title = $('#thickboxHeaderTitle').val();
				ShowAlertPopup(title);
				changeAddFavoriteButton('favorite');
				break;
			case 3: //favourite failure
				$('#faveButton').show();
				var title = $('#alertHeaderTitle').val();
				ShowErrorPopup(title);
				break;
			case 5: // user has favourite
				changeAddFavoriteButton( 'favorite' );
				break;
			case 6: // user does not have favourite
				changeAddFavoriteButton();
				break;
		}
	});
}


function changeAddFavoriteButton( type )
{
    switch( type )
    {
        // show link to my favorites
        case 'favorite':
                $('#faveButton').hide();
   				$('#add_to_favorites_message').show();
                break;
        // show add to my favorite button
        default:
                $('#add_to_favorites_message').hide();
   				$('#faveButton').show();
    }
}

function ShowErrorPopup( title ) {
    // this should show error page, not add favorite message
	tb_show(title, "/MyLN/ErrorFavourite?height=120&amp;width=350&class=alert", null);
}


function ShowAlertPopup( title ) {
	// display this alert just once
	if( document.showingAlertPopup == true )
		return false;
	else
		document.showingAlertPopup = true;
		
	if( $.cookie('doNotshowPopupAlert') )
		return false;
		
	tb_show(title , "/MyLN/AddFavourite?height=210&amp;width=380&class=alert", null);
}

function ShowFacebookDisconnectPopup(title) {
    tb_show(title, "/Account/FacebookDisconnect?height=80&amp;width=380&class=alert", null);
}
