﻿$(document).ready(function () {
    SaveAPic.CoreUI.ActivateNavigation();
    //SaveAPic.CoreUI.StyleButtons();
    SaveAPic.CoreUI.SetExampleText();
    SaveAPic.CoreUI.InitializeSearch();
});

if (typeof SaveAPic == 'undefined') var SaveAPic = {};
SaveAPic.CoreUI = SaveAPic.CoreUI || {};

/*-------------------------------------------------*/
/*----------------Core UI Scripts------------------*/
/*-------------------------------------------------*/

SaveAPic.CoreUI.ActivateNavigation = function () {
    $('#TopMenu li').hover(
        function () {
            //show its submenu  
            $('ul', this).slideDown(100);

        },
        function () {
            //hide its submenu  
            $('ul', this).slideUp(100);
        }
    );
}

SaveAPic.CoreUI.SetExampleText = function () {
    $('input[type=text][title!=""]').each(function () {
        if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
        if ($(this).val() == $(this).attr('title')) $(this).addClass('ExampleText');
    }).focus(SaveAPic.CoreUI.SwitchText).blur(SaveAPic.CoreUI.SwitchText);

    $('form').submit(function () {
        $(this).find('input[type=text][title!=""]').each(function () {
            if ($(this).val() == $(this).attr('title')) $(this).val('');
        });
    });
}

SaveAPic.CoreUI.SwitchText = function () {
    if ($(this).val() == $(this).attr('title'))
        $(this).val('').removeClass('ExampleText');
    else if ($.trim($(this).val()) == '')
        $(this).addClass('ExampleText').val($(this).attr('title'));
}

SaveAPic.CoreUI.InitializeSearch = function () {
    SaveAPic.CoreUI.BindEnterKey("#SearchQuery", function () {
        SaveAPic.CoreUI.Search();
    });

    $("#SearchForm span.glass i").click(function () {
        SaveAPic.CoreUI.Search();
    });

    //Resetup the switch text since I removed all bound events
    $("#SearchQuery").focus(SaveAPic.CoreUI.SwitchText).blur(SaveAPic.CoreUI.SwitchText);
}

SaveAPic.CoreUI.SearchFromPage = function () {
    var query = $(".searchField").val();
    var encodedQuery = encodeURIComponent(query)
    window.location = "/Search.aspx?q=" + encodedQuery;
}

SaveAPic.CoreUI.Search = function () {
    var query = $("#SearchQuery").val();

    if (query == "Search Photos") query = "";

    var encodedQuery = encodeURIComponent(query)
    window.location = "/Search.aspx?q=" + encodedQuery;
}


/*-------------------------------------------------*/
/*------------JQuery Extension Methods-------------*/
/*-------------------------------------------------*/
jQuery.fn.center = function () {
    this.css("position", "absolute");

    var top = ($(window).height() - this.height()) / 2 + $(window).scrollTop();
    var left = ($(window).width() - this.width()) / 2 + $(window).scrollLeft();

    if (top < 0) top = 17;

    this.css("top", top + "px");
    this.css("left", left + "px");
    return this;
}

/*-------------------------------------------------*/
/*--------------------Core Events------------------*/
/*-------------------------------------------------*/
SaveAPic.CoreUI.ProcessInternalEvent = function (url) {
    var homeReg = /^\/\d+\/Albums\/?$/;
    if (homeReg.test(url)) {
        $("#BCButPrevious1").removeClass("bcForceHover");
        $("#ViewAlbum").removeClass("bcForceHover");

        SaveAPic.Album.CloseEdit();
        SaveAPic.User.LoadAlbums(globalUserId, 1);
        SaveAPic.User.MoveToSlide();
        SaveAPic.Upload.ShowUploadPhotos();
        if (!_isUserLoggedIn) SaveAPic.CoreUI.ShowLoginMessageGeneric();
        return;
    }

    var homeRegPaged = /^\/\d+\/Albums\/?\?p=\d+/;
    if (homeRegPaged.test(url)) {
        $("#BCButPrevious1").removeClass("bcForceHover");
        $("#ViewAlbum").removeClass("bcForceHover");

        var page = $.address.parameter("p");
        //globalPage = page;

        SaveAPic.Album.CloseEdit();
        SaveAPic.User.LoadAlbums(globalUserId, page);
        SaveAPic.User.MoveToSlide();
        SaveAPic.Upload.ShowUploadPhotos();
        return;
    }

    var viewAlbum = /^\/\d+\/Albums\/\d+\/Photos\/?$/;
    if (viewAlbum.test(url)) {
        $("#ViewAlbum").removeClass("bcForceHover");

        SaveAPic.User.UpdatePagingLink();
        SaveAPic.User.ShowBackIcon();

        var albumId = SaveAPic.CoreUI.GetValue(url, "Albums");
        SaveAPic.Album.LoadAlbum(albumId);
        SaveAPic.Upload.ShowAddMorePhotos();
        return;
    }

    var photosReg = /^\/\d+\/Albums\/\d+\/Photos\/\w+\/?/;
    if (photosReg.test(url)) {

        SaveAPic.Album.ShowBackIcon();

        var albumId = SaveAPic.CoreUI.GetValue(url, "Albums");
        var photoId = SaveAPic.CoreUI.GetValue(url, "Photos");
        var mode = SaveAPic.CoreUI.GetValue(url, "Mode");
        SaveAPic.Album.CloseEdit();
        SaveAPic.Upload.ShowAddMorePhotos();
        if (mode == null) mode = "simple";
        if (globalPhotos == null) SaveAPic.Photo.ShowPhotoDeepLink(albumId, photoId, mode);
        else SaveAPic.Photo.ShowPhoto(photoId, mode);
        return;
    }
}

//External events can't be trusted so special caution must be taken
//to ensure that the state of site is accurately represented.
SaveAPic.CoreUI.ProcessExternalEvent = function (url) {
    var pageUserId = SaveAPic.User.GetPageUserId();
    if (pageUserId != _pageUserId) {
        var url = window.location + "";
        url = url.replace("/#!", "");
        window.location = url;
    }

    var homeReg = /^\/\d+\/Albums\/?$/;
    if (homeReg.test(url)) {
        $("#BCButPrevious1").removeClass("bcForceHover");
        $("#ViewAlbum").removeClass("bcForceHover");

        SaveAPic.Album.CloseEdit();
        SaveAPic.User.LoadAlbums(globalUserId, 1);
        SaveAPic.User.MoveToSlide();
        SaveAPic.Upload.ShowUploadPhotos();
        if (!_isUserLoggedIn) SaveAPic.CoreUI.ShowLoginMessageGeneric();
        return;
    }

    var homeRegPaged = /^\/\d+\/Albums\/?\?p=\d+/;
    if (homeRegPaged.test(url)) {
        $("#BCButPrevious1").removeClass("bcForceHover");
        $("#ViewAlbum").removeClass("bcForceHover");

        var page = $.address.parameter("p");
        SaveAPic.Album.CloseEdit();
        SaveAPic.User.LoadAlbums(globalUserId, page);
        SaveAPic.User.MoveToSlide();
        SaveAPic.Upload.ShowUploadPhotos();
        SaveAPic.CoreUI.HideLoginMessage();
        return;
    }

    var viewAlbum = /^\/\d+\/Albums\/\d+\/Photos\/?$/;
    if (viewAlbum.test(url)) {
        $("#ViewAlbum").removeClass("bcForceHover");

        SaveAPic.User.ShowBackIcon();

        var albumId = SaveAPic.CoreUI.GetValue(url, "Albums");
        SaveAPic.Album.ShowAlbumDeepLink(albumId);
        SaveAPic.Upload.ShowAddMorePhotos();
        return;
    }

    var photosReg = /^\/\d+\/Albums\/\d+\/Photos\/\w+\/?/;
    if (photosReg.test(url)) {

        SaveAPic.Album.ShowBackIcon();

        var albumId = SaveAPic.CoreUI.GetValue(url, "Albums");
        var photoId = SaveAPic.CoreUI.GetValue(url, "Photos");
        var mode = SaveAPic.CoreUI.GetValue(url, "Mode");
        SaveAPic.Album.CloseEdit();
        if (mode == null) mode = "simple";
        SaveAPic.Upload.ShowAddMorePhotos();
        SaveAPic.Photo.ShowPhotoDeepLink(albumId, photoId, mode);
        return;
    }
}

SaveAPic.CoreUI.GetValue = function (url, name) {
    url = url.toLowerCase();
    name = name.toLowerCase();

    var searchString;
    if (name != "/") searchString = name + "/";
    else searchString = name;

    var startIndex = url.indexOf(searchString);
    if (startIndex == -1) return null;
    startIndex += searchString.length;

    var startOfValue = url.substring(startIndex, url.length);

    var nextSlash = startOfValue.indexOf("/");
    if (nextSlash == -1) return startOfValue;
    else return startOfValue.substring(0, nextSlash);
}

var _errorID = 0;
SaveAPic.CoreUI.ShowError = function (message, traceInformation) {
    _errorID++;

    if ((message == undefined) || (message == "")) {
        message = "Oops, an error occured.  Please try again in a few seconds."
    }
    if ($("#ErrorMessage").length == 0) {
        var errorMessageDiv = "<div id='ErrorMessage'>" + message + "</div>";
        $('body').append(errorMessageDiv)
    }

    //Set the position
    var winWidth = $(window).width();
    var contentWidth = $("#ErrorMessage").width();

    var leftPosition = (winWidth / 2) - (contentWidth / 2);
    $("#ErrorMessage").css('left', leftPosition + "px");

    $("#ErrorMessage").show();
    setTimeout('SaveAPic.CoreUI.HideError(' + _errorID + ')', 6000);
}

SaveAPic.CoreUI.HideError = function (errorId) {
    //If a new error occured do not hide the message from the previous one.
    if (_errorID == errorId) {
        $("#ErrorMessage").hide();
    }
}

SaveAPic.CoreUI.ShowLoginMessageWallPost = function () {
    if (!_isUserLoggedIn) SaveAPic.CoreUI.ShowLoginMessage("This wall post is not shared publicly. Please login to experience SaveAPic to the fullest.", true);
    else SaveAPic.CoreUI.ShowLoginMessage("This wall post is not shared publicly.", true);
    $("#WallPostHTML .loadingContent").html("Sorry, this post is unavailable.")
}

SaveAPic.CoreUI.ShowLoginMessageAlbum = function () {
    if (!_isUserLoggedIn) SaveAPic.CoreUI.ShowLoginMessage("This album is not shared publicly. Please login to experience SaveAPic to the fullest.", true);
    else SaveAPic.CoreUI.ShowErrorMessage("This album is not shared publicly.", true);
    $("#Photos .loading").removeClass("loading");
}

SaveAPic.CoreUI.ShowLoginMessageGeneric = function () {
    SaveAPic.CoreUI.ShowLoginMessage("Some photos are not shared publicly.  Please login to experience SaveAPic to the fullest.", false);
}

SaveAPic.CoreUI.ShowLoginMessageProfile = function () {
    if (!_isUserLoggedIn) SaveAPic.CoreUI.ShowLoginMessage(_firstName + " " + _lastName + " does not share all photos publicly.  Please login to experience SaveAPic to the fullest.", false);
}

SaveAPic.CoreUI.ShowLoginMessage = function (content, shouldSlide) {
    $("#ErrorIcon").hide();
    $("#LoginLink").show();

    var returnUrl = window.location + "";
    returnUrl = returnUrl.substring(returnUrl.indexOf(".com/") + 4, returnUrl.length);
    returnUrl = returnUrl.replace("#!/", "");
    returnUrl = encodeURI(returnUrl);

    $("#LoginLink").attr("href", "/FbOauth/?ReturnUrl=" + returnUrl);
    $("#NoAccessMessage").html(content);
    if (shouldSlide) $("#NoAccessNotLoggedInMessage").slideDown("slow");
    else $("#NoAccessNotLoggedInMessage").show();
}

SaveAPic.CoreUI.ShowErrorMessage = function (content, shouldSlide) {
    $("#ErrorIcon").show();
    $("#LoginLink").hide();

    $("#NoAccessMessage").html(content);
    if (shouldSlide) $("#NoAccessNotLoggedInMessage").slideDown("slow");
    else $("#NoAccessNotLoggedInMessage").show();
}


SaveAPic.CoreUI.HideLoginMessage = function (content) {
    $("#NoAccessNotLoggedInMessage").slideUp("slow");
}

SaveAPic.CoreUI.DisableButton = function (element, content) {
    $(element).attr("disabled", "disabled");
    $(element).css("cursor", "wait");
    $(element).attr("value", content);
}

SaveAPic.CoreUI.EnableButton = function (element, content) {
    $(element).removeAttr("disabled", "disabled")
    $(element).removeAttr("style", "cursor:wait;")
    $(element).attr("value", content)
}

SaveAPic.CoreUI.ShowTempNotification = function (element, content) {
    //Hide if it already exists
    $(element + "_ButtonWait").remove();

    //Create the temp notification
    var newId = element.replace("#", "").replace(".", "") + "_ButtonWait";
    $(element).after("<span class='tempNotification' id='" + newId + "'>" + content + "</span>");
    setTimeout('SaveAPic.CoreUI.HideTempNotification("' + element + '")', 4000);
}

SaveAPic.CoreUI.HideTempNotification = function (element) {
    $(element + "_ButtonWait").fadeOut('slow', function () {
        $(element + "_ButtonWait").remove();
    });
}

SaveAPic.CoreUI.BindEnterKey = function (focusElement, enterFunc) {
    $(focusElement).unbind();

    $(focusElement).bind('keyup', function (e) {
        if (e.keyCode == 13) { enterFunc(); }
    });
}

var _controlHandler = null;
SaveAPic.CoreUI.BindControlBehavior = function () {
    if (_controlHandler != null) $(".ajaxIt").unbind('click', _controlHandler);

    _controlHandler = function (eventObject) {
        if (eventObject.ctrlKey) {
            var url = window.location + "";
            var eventValue = $(this).attr('href');
            url = url.substring(0, url.indexOf("/#!") + 4) + eventValue;
            window.open(url, '_blank').blur();

            eventObject.preventDefault();
            return false;
        }
    };

    $(".ajaxIt").bind('click', _controlHandler, true);
}
