﻿var addthis_config = { "data_track_clickback": true };
var addthis_share = { url: "http://www.1christian.net/guitar/setlist.aspx", title: "RWTC Set List", email_template: "RWTC-Template",
    templates: {
        twitter: 'check out {{url}} (from @example_dot_com)'
    }
}
//Read cookies and set page accordingly
var LoggedIn = $.cookie('LoggedIn');
var UserID = $.cookie("userid");
$(function () {
    $.reject({
        reject: {}, // Reject all renderers for demo
        display: ['firefox', 'chrome', 'msie', 'safari'], // Displays only firefox, chrome, and opera
        imagePath: 'images/', // Path where images are located  
        closeESC: true, // allow use of ESC key to close                
        closeCookie: true // Set cookie to remmember close for this session 
    });
    $(".loginTable").addClass("hidden");
    $("#saveLogin").hide();
    $(".lblPwdRec").hide();
    var fname = location.pathname.toLowerCase();
    if (fname.indexOf("top25.aspx") > -1) {
        $("#rssIcon").attr({ title: "Top 25 RSS feed", alt: "Top 25 RSS feed" });
        $("#rssIcon").click(function () {
            window.location = "http://www.1christian.net/rss/rwtc-top25.aspx"
        });
        $(".spotifyIcon").attr({ title: "Listen to Top 25 on Spotify", alt: "Listen to Top 25 on Spotify" });
        $(".spotifyIcon").click(function () {
            window.location = "http://open.spotify.com/user/123859608/playlist/7Hl6eEgIIHp2GrjEZJ2z8X"
        });
    };
    if (fname.indexOf("newtab.aspx") > -1) {
        $("#rssIcon").attr({ title: "New Songs RSS feed", alt: "New Songs RSS feed" });
        $("#rssIcon").click(function () {
            window.location = "http://www.1christian.net/rss/rwtc-newsongs.aspx?d=7"
        });
        $(".spotifyIcon").attr({ title: "Listen to the New Songs on Spotify", alt: "Listen to the New Songs on Spotify" });
        $(".spotifyIcon").click(function () {
            window.location = "http://open.spotify.com/user/123859608/playlist/4vrwe3tkLIaI8FjDpdQ9Dt"
        });
    };
    //determine if user is logged in and set page attributes accordingly
    if (LoggedIn != null) {
        $(".lblLogin").hide();
        $(".lblLogout").show();
        $(".loginTable").addClass("hidden");
        $(".lblMyAccount").show();
        $(".lblSignUp").hide();
        $(".slAdd").show();
        $(".isfav").show();
        if (!isiPad() && $("#hdnslideout").val() != 'no') {
            initiateSlideOut();
        }
    } else {
        $(".lblLogin").show();
        $(".lblLogout").hide();
        $(".lblMyAccount").hide();
        $(".lblSignUp").show();
        $(".slAdd").hide();
        $(".isfav").hide();
        showWelcome();
    };

    $("#expandAbout").hover(
        function () {
            $("#divexpandAbout:hidden").show();
        },
        function () {
            $("#divexpandAbout").hide();
        });

    $("#expand").hover(
        function () {
            $("#divexpand:hidden").show();
        },
        function () {
            $("#divexpand").hide();
        });
    //Other Areas Drop down 
    $("#expandAreas").hover(
        function () {
            $("#divexpandAreas:hidden").show();
        },
        function () {
            $("#divexpandAreas").hide();
        });

    $("#expandfreemonth").hover(
        function () {
            $("#divfreemonth:hidden").show();
        },
        function () {
            $("#divfreemonth").hide();
        });
    //Help Drop down
    $("#expandHelp").hover(
        function () {
            $("#divexpandHelp:hidden").show();
        },
        function () {
            $("#divexpandHelp").hide();
        });
    //Categories Drop Down
    $("#expandCategories").hover(
    function () {
        $("#divexpandCategories:hidden").show();
    },
    function () {
        $("#divexpandCategories").hide();
    });

    //Click function for all Login functions
    $(".lblLogin").click(function () {
        if ($(".loginImage").is(":hidden")) {
            $(".loginImage").slideDown(500);
            $(".loginButton").slideDown(500);
            $(".loginTable").addClass("hidden").fadeTo(0, 0, function () {
                $(this).removeClass("hidden")
            }).fadeTo(0, 0).fadeTo(500, 0).fadeTo(0, 1);
            $("#saveLogin").fadeIn(500);
            $(".lblPwdRec").fadeIn(500);
            $(".txtUserName").focus();
        } else {
            $(".loginImage").slideUp(200);
            $(".loginButton").slideUp(200);
            $(".loginTable").toggleClass("hidden");
            $("#saveLogin").hide();
            $(".lblPwdRec").hide();
        }
    });

    //bind click event to search button
    function deleteScrollTopCookie() {
        $("#songList").scrollTop(0);
        $.cookie('st', '0');
    }
    $(".searchIcon").bind("click", function (e) {
        deleteScrollTopCookie();
        window.location = "search.aspx?searchMain=" + $("#searchMain").val();
    });
    $("#searchMain").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "services/wsvc_rwtc_search.asmx/search",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{"searchterm":"' + $("#searchMain").val() + '"}',
                success: function (data) {
                    response($.map(data.d, function (item) {
                        if (item.TabID == 0) {
                            return {
                                label: 'artist:' + item.ArtistName,
                                value: item.ArtistName
                            }
                        }
                        else {
                            return {
                                label: item.Songtitle,
                                value: item.Songtitle
                            }
                        }
                    }));
                }
            });
        },
        minLength: 2,
        select: function (event, ui) {
            deleteScrollTopCookie();
            window.location = "search.aspx?searchMain=" + ui.item.value;
        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
    //bind keypress "enter" to search form
    $("#searchMain").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            deleteScrollTopCookie();
            window.location = "search.aspx?searchMain=" + $("#searchMain").val();
            return false;
        }
    });
    //search for default.aspx
    //bind click event to search button in Default.aspx
    $(".searchIconAdv").bind("click", function (e) {
        //get query to search.aspx
        deleteScrollTopCookie();
        window.location = "search.aspx?searchType=" + $("#searchType").val() + "&searchTerms=" + $(".searchBarAdv").val();
    });

    //bind keypress "enter" to search form in Default.aspx
    $(".searchBarAdv").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            deleteScrollTopCookie();
            window.location = "search.aspx?searchType=" + $("#searchType").val() + "&searchTerms=" + $(".searchBarAdv").val();
        }
    });
    //bind keypress "enter" to search form in Default.aspx
    $(".searchIconAdv").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            deleteScrollTopCookie();
            window.location = "search.aspx?searchType=" + $("#searchType").val() + "&searchTerms=" + $(".searchBarAdv").val();
        }
    });

    //bind click event to login button
    $("#loginButton").bind("click", function (e) {
        doLogin();
        return false; //not to post the  form physically
    });

    //bind keypress "enter" to login form
    $("#txtUserName").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            doLogin()
            return false; //not to post the  form physically
        }
    });
    $("#txtPassword").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            doLogin()
            return false; //not to post the  form physically
        }
    });

    // ============= Set List =====================
    $("#divSetListName").click(function () {
        $("#divSetListName").hide();
        $("#editSetListName").show();
    });
    $("#divUsedDate").click(function () {
        $("#divUsedDate").hide();
        $("#editUsedDate").show();
        $("#txtUsedDate").datepicker({
            numberOfMonths: 2,
            showButtonPanel: true
        });
        /*    $("#anim").change(function () {
        $("#datepicker").datepicker("option", "showAnim", $(this).val());
        });
        */
    });
    $(".slAdd").click(function (e) {
        //addToSetList();
        var $c = $("<div/>");
        var tabid = $(this).attr("id");
        tabid = tabid.substring(6);
        $c.addClass("ctlAddclone");
        $c.css("top", "170px");
        var startx = $(window).width()
        pos = $(this).position();
        var starty = parseInt(pos.top) + 240;
        startx = parseInt(startx - 970) + 770;
        $c.css("left", startx);
        $c.css("top", starty);
        $c.appendTo("#wrapper");

        startx = parseInt($(window).width() - startx);
        starty = starty - 170;

        $c.animate({
            left: '+=' + startx,
            top: '-=' + starty
        }, 700, function () {
            // Animation complete.
            $('#setlist_slideout').animate({ right: '-3px' }, 200).addClass('open');
            $c.remove();
            addListSongToSetList(tabid)
        });
    });
    $("#txtSetListName").blur(function () {
        updateSetListName();
    });
    $("#txtSetListName").keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            updateSetListName();
        }
    });
    $("#txtUsedDate").blur(function () {
        updateUsedDate();
    });
    $("#txtUsedDate").keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            updateUsedDate();
        }
    });
    $(".remsong").click(function () {
        removeSong($(this).attr("id"));
    });
    $(".changeSetList").click(function () {
        $("#setlistwrapper").hide();
        $("#setlist_noset").hide();
        $("#divselectlist").slideDown();
        getListOfSets(UserID)
    });
    $("#hideChange").click(function () {
        $("#divselectlist").hide();
        var setid = $.cookie('SetListID');
        if (parseInt(setid) > 0) {
            $("#setlistwrapper").slideDown();
        }
        else {
            $("#setlist_noset").slideDown();
        }
    });
    $("#txtJoinEmail").bind("keypress", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            saveEmail($("#txtJoinEmail").val(), "", "", "", "", "");
        }
    });
    // Begin jQuery for adding/controlling "Favorites" featuers
    // =======================================================================
    $('.isfav').click(function () {
        var id = this.id;
        id = id.substring(3);
        // Get the last section of the URL to send to the join page
        // This will redirect the user back to this page after joining RWTC
        var url = window.location.pathname.split('/');
        var urlEnd = url[2];
        if (LoggedIn == null) {
            //If the user is not Logged in... Give them the login dialog window
            loginDialog(urlEnd);
        } else if ($(this).hasClass('favAdded')) {
            // If the item has had its class changed from "favAdd" to "favAdded" run the remove function
            favoritesRemove(id);
        } else {
            // If the item is not already favorited, run the add function
            favoritesAdd(id);
        }
    });
    function favoritesAdd(id) {
        $.post("ajax.aspx", { action: "favAdd", UserID: UserID, TabID: id },
                function (data) {
                    if (data == '0') {
                        // This is the error response
                        alert("Oops! An error happened while saving this favorite")
                    } else if (data == '1') {
                        // This is for a successful db add
                        $("#fav" + id).removeClass().addClass('favAdded');
                        $("#fav" + id).attr("title", "Click to remove this song from your favorites list!")
                    }
                });
    }
    function favoritesRemove(id) {
        // This function controls the removing of specific entries from RWTC_Favorites
        $.post("ajax.aspx", { action: "favRem", UserID: UserID, TabID: id },
            function (data) {
                if (data == '0') {
                    // This is the error response
                    alert("Oops! Unable to remove this song from Favorites");
                } else if (data == '1') {
                    // toggle <div> classes
                    // This is for a successful db remove
                    $("#fav" + id).removeClass().addClass('favAdd');
                    $("#fav" + id).attr("title", "Click to add this song to your favorites list!")
                }
            });
    }
});                                                           //end brackets for document ready function

function initiateSlideOut() {
    if (LoggedIn != null) {
        $("#setlist_slideout").removeClass("hide");
        $(".handle").attr("title", "click to slide");
    
        $('#setlist_slideout').tabSlideOut({
            tabHandle: '.handle',                     //class of the element that will become your tab
            pathToTabImage: 'img/setlist_tab.png', //path to the image for the tab //Optionally can be set using css
            imageHeight: '122px',                     //height of tab image           //Optionally can be set using css
            imageWidth: '40px',                       //width of tab image            //Optionally can be set using css
            tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
            speed: 300,                               //speed of animation
            action: 'click',                          //options: 'click' or 'hover', action to trigger animation
            topPos: '150px',                          //position from the top/ use if tabLocation is left or right
            leftPos: '20px',                          //position from left/ use if tabLocation is bottom or top
            fixedPosition: true                      //options: true makes it stick(fixed position) on scroll
        });
        //make song list draggable
        //$(".liSong").draggable({ cursor: "move", cursorAt: { cursor: "move", top: 10, left: 10 }, helper: function () { return $(this).clone().width(300); }, revert: "invalid", opacity: "0.7", containment: "window", connectToSortable: "#setList_songs", zIndex: 2700 });

        $("#setList_songs, #setList_songs").sortable({
            update: function (event, ui) {
                var idx = $(ui.item).parent().children().index(ui.item);
                var parent = $(ui.item).parent().attr("id");
                idx++;
                var songid = $(ui.item).attr("id");
                changeSongOrder(songid, idx);
                if (parent == 'setList_songs') {
                    reloadSetListTab();
                }
            }
    }).disableSelection();
    var setid = $.cookie('SetListID');
    if (parseInt(setid) > 0)
        loadSetList(setid);
    }
    if (isiPad()) {
        $("#setlist_slideout").css("display", "none");
    }
}
function addListSongToSetList(tabid) {
    if (tabid == null) {
        tabid = $('#hdnTabID').val();
    }
    var songkey = $("#"+tabid).find(".songKey").find('strong').html();
    var $songTitle = $($("#" + tabid + " .songTitle")).clone();

    var ret = addSongToSetList(tabid, songkey)
    if (parseInt(ret) > 0) {
        //flytoslide()
        var $addsong;
        //var $artist = $(".artist a").clone().addClass("artistName");
        var $artist = $($("#" + tabid + " .artistName")).clone();
        if ($artist.html() == null) {
            $artist = $("<a/>");
            $artist.addClass("artistName");
            $artist.attr("href", "artist.aspx?ArtID=0")
        }
        $artist.attr("title", "view artist")
        $addsong = $('<li/>').html('<div id="remsong-' + ret + '" title="remove song" class="remsong"><span class="ui-icon ui-icon-closethick"></span></div><span class="songKey"><strong>' + songkey + '</strong></span> - <a href="show.aspx?TabID=' + tabid + '&songkey=' + songkey + '" class="songTitle" title="view song">' + $songTitle.html() + '</a><br/>');
        $($artist).appendTo($addsong);
        $addsong.attr("id", ret);
        $addsong.addClass('liSong ui-draggable rounded');
        $($addsong).appendTo("#setList_songs").show("slow");
        reloadSetListTab();

        $(".remsong").unbind('click');
        $(".remsong").click(function () {
            removeSong($(this).attr("id"));
        });
        setTimeout(function () { $('#setlist_slideout').animate({ right: '-3px' }, 300).addClass('open'); }, 100);
    }
}
function addSongToSetList(songid, songkey) {
    var ret;
    var setID = $("#divSetID").html();
    var data = { "setID": setID, "songID": songid, "songKey": songkey }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/addsongtosetlist.ashx",
        dataType: "text",
        async: false,
        success: function (data) {
            ret = data;
        },
        error: function (e) {
            //alert('Set List - Add Song\n' + e.d);
            ret = 0;
        }
    });
    return ret;
}
function removeSong(ssid) {
    var id = ssid.substring(8);
    var data = { "setSongID": id }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/removesetlistsong.ashx",
        dataType: "text",
        async: false,
        success: function (data) {
            if (parseInt(data) > 0) {
                id = "#" + id;                
                var $songslide = $("#setList_songs").find(id);
                $songslide.slideUp(function () { $songslide.remove(); });
                //$(id).slideUp(function () { $(id).remove(); });

                reloadSetListTab();
            }
            else {
                //alert("Unable to remove song : " + data);
            }
        },
        error: function (e) {
            alert('Set List - Remove Song\n' + e.d);
        }
    });
}
function changeSongOrder(songid, neworder) {
    var data = { "setSongID": songid, "songorder": neworder }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/changesetlistsongorder.ashx",
        dataType: "text",
        success: function (data) {
            if (parseInt(data) > 0) {
                return 1;
            }
            else {
                alert('Song Order was not saved');
                return 0;
            }
        },
        error: function (e) {
            alert('Set List - Change Order\n' + e.d);
            return 0
        }
    });
}
function createSetList() {
    $("#setlistwrapper").hide();
    $("#divselectlist").hide();
    $("#setlist_noset").show();
    var setlistname = 'New Set List' //$("#divSetListName").html();

    var data = { "SetListName": fixup(setlistname) }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/createsetlist.ashx",
        dataType: "text",
        async: false,
        success: function (data) {
            if (parseInt(data) > 0) {
                $("#divSetID").html(data);
                var today = new Date();
                $("#divCreatedate").html("created on " + today);
                $("#divSetListName").html(setlistname);
                $("#txtSetListName").val(setlistname);
                $("#divSetListName").show();
                $("#editSetListName").hide();
                $("#setList_songs").empty();
                $("#setlistwrapper").show();
                $("#setlist_noset").hide();

                var options = { path: '/', expires: 10 };
                $.cookie('SetListID', data, options);

                var $newset = $("<div/>").html('<div class="setlist" id="setrow-' + data + '"><div class="setlist1">New Set List</div><div class="setlist2">&nbsp;</div><div class="setlist3">0</div></div><div class="setlist4" title="remove Set List" id="remsetlist-' + data + '"><span class="remsetlist ui-icon ui-icon-closethick" id="' + data + '"></span></div>')
                $newset.css("height", "20");
                $("#rptSetList").prepend($newset);
                $(".remsetlist").unbind();
                $(".remsetlist").click(function () {
                    var id = $(this).attr("id");
                    deleteSetList(id)
                });
            }
            else {
                alert('Set List Did Not Save');
            }
        },
        error: function (e) {
            alert('Set List - Create Set\n' + e.d);
        }
    });
}
function loadSetList(setid) {
    $("#setlistwrapper").show();
    $("#setlist_noset").hide();
    $("#divselectlist").hide();
    $("#divSetID").html(setid);
    var data = { "setID": setid }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/getsetlist.ashx",
        dataType: "text",
        async: false,
        success: function (data) {
            //alert("success ... loading ...\n" + data);
            var setlist;
            setlist = data.split("\n");
            var set;
            set = setlist[0].split("\t");
            $("#divSetListName").html(set[1]);
            $("#txtSetListName").val(set[1]);
            $("#divSetListName").show();
            $("#editSetListName").hide();
            $("#divSetID").val(set[0]);
            addthis_share = { "url": "http://www.1christian.net/guitarbeta/setlist.aspx?setid=" + set[0], "title": "RWTC Set List", "email_template": "RWTC-Template" }
            $("#addthis_button_facebook").attr("addthis:url", "http://www.1christian.net/rwtcross/setlist.aspx?SetID=" + set[0]);
            $("#addthis_button_twitter").attr("addthis:url", "http://www.1christian.net/rwtcross/setlist.aspx?SetID=" + set[0]);
            $("#addthis_button_googlebuzz").attr("addthis:url", "http://www.1christian.net/rwtcross/setlist.aspx?SetID=" + set[0]);
            $("#addthis_button_email").attr("addthis:url", "http://www.1christian.net/rwtcross/setlist.aspx?SetID=" + set[0]);

            var options = { path: '/', expires: 10 };
            $.cookie('SetListID', set[0], options);
            $("#divCreatedate").html("created on " + set[3]);
            $("#divcreatedate").html("created on " + set[3]);

            if (set[5] == "12:00:00 AM") {
                $("#divUsedDate").html("used on ");
                $("#divuseddate").html("used on ");
            }
            else {
                $("#divUsedDate").html("used on " + set[5]);
                $("#divuseddate").html("used on " + set[5]);
                $("#txtUsedDate").val(set[5]);
            }

            $("#setList_songs").empty();
            $("#setlistsonglist").empty();

            for (i = 1; i < setlist.length - 1; i++) {
                set = setlist[i].split("\t");
                if (set[2] != undefined) {
                    var $addsong;
                    if (set[4] == 'null') { set[4] = '' }
                    $addsong = $('<li/>').html('<div id="remsong-' + set[1] + '" title="remove song" class="remsong"><span class="ui-icon ui-icon-closethick"></span></div><span class="songKey"><strong>' + set[4] + '</strong></span> - <a href="show.aspx?TabID=' + set[2] + '&songkey=' + set[4] + '" class="songTitle" title="view song">' + set[3] + '</a><br/><a href="artist.aspx?ArtID=' + set[5] + '" class="artistName" title="view artist">' + set[6] + '</a>');
                    $addsong.attr("id", set[1]);
                    $addsong.addClass('liSong ui-draggable rounded');
                    $($addsong).appendTo("#setList_songs").show("slow");
                    $($addsong).clone().appendTo("#setlistsonglist").show("slow");
                }
            }
            $(".remsong").unbind('click');
            $(".remsong").click(function () {
                removeSong($(this).attr("id"));
            });
        },
        error: function (e) {
            alert('Set List - Load Set\n' + e.d);
            return false
        }
    });
}
function updateSetListName() {
    if ($("#divSetListName").html() != $("#txtSetListName").val()) {
        var setid = $("#divSetID").html();

        var data = { "setID": setid, "SetListName": fixup($("#txtSetListName").val()) }
        $.ajax({
            type: "POST",
            data: data,
            url: "handler/updatesetlist.ashx",
            dataType: "text",
            success: function (data) {
                if (data == 'true') {
                    $("#divSetListName").html($("#txtSetListName").val())
                    reloadSetListTab();
                }
                else {
                    alert("Set Name update failed");
                    $("#txtSetListName").val($("#divSetListName").html())
                }
            },
            error: function (e) {
                alert('Set List - Update Name\n' + e.d);
                return 0
            }
        });
    }

    $("#divSetListName").show();
    $("#editSetListName").hide();
}
function updateUsedDate() {
    if ($("#divUsedDate").html() != $("#txtUsedDate").val()) {
        var setid = $("#divSetID").html();

        var data = { "setID": setid, "dateUsed": fixup($("#txtUsedDate").val()) }
        $.ajax({
            type: "POST",
            data: data,
            url: "handler/updateuseddate.ashx",
            dataType: "text",
            success: function (data) {
                if (data == 'true') {
                    $("#divUsedDate").html("used on " + $("#txtUsedDate").val())
                    reloadSetListTab();
                }
                else {
                    alert("Used Date update failed\ninvalid date forumla");
                    $("#txtUsedDate").val($("#divUsedDate").html())
                }
            },
            error: function (e) {
                alert('Set List - Date Update\n' + e.d);
                return 0
            }
        });
    }

    $("#divUsedDate").show();
    $("#editUsedDate").hide();
}
function deleteSetList(setid) {
    //remove from database
    var data = { "setListID": setid }
    $.ajax({
        type: "POST",
        data: data,
        url: "handler/deletesetlist.ashx",
        dataType: "text",
        success: function (data) {
            if (parseInt(data) == 1) {
                var rowid = "#setrow-" + setid;
                //delete cookie if active
                var cook = $.cookie('SetListID');
                if (cook == setid) {
                    var options = { path: '/', expires: -10 };
                    $.cookie('SetListID', data, options);
                }
                //clear slideout if active
                cook = $("divSetID").html();
                if (cook == setid) {
                    $("#setlistwrapper").hide();
                    $("#setlist_noset").show();
                }
                //remove row from set list on favorites page
                $(rowid).parent().slideUp();
            }
            else {
                alert("Delete failed");
            }
        },
        error: function (e) {
            alert('Set List - Delete Set\n' + e.d);
            return 0
        }
    });
}
function reloadSetListTab() {
    // reload if the set list tab is on the page
    var url = window.location.pathname.toLowerCase();
    
    if (url.indexOf("favorites.aspx") != -1) { 
        var setID = $("#divSetID").html();

        $("#tabs-" + setID + " #setlistname").html($("#divSetListName").html());
        $("#tabs-" + setID + " #divuseddate").html($("#divUsedDate").html());
        $("#tabs-" + setID + " #setlistsonglist").empty();
        $('#setList_songs li').each(function (i) {
            //alert($(this).html());
            $(this).clone().appendTo("#tabs-" + setID + " #setlistsonglist");
        });
    }

    $(".remsong").unbind('click');
    $(".remsong").click(function () {
        removeSong($(this).attr("id"));
    });
    $("#tabs-" + setID + " #setlistsonglist, #tabs-" + setID + " #setlistsonglist").unbind();
    $("#tabs-" + setID + " #setlistsonglist, #tabs-" + setID + " #setlistsonglist").sortable({
        update: function (event, ui) {
            var idx = $(ui.item).parent().children().index(ui.item);
            var parentsetid = $(ui.item).parent().parent().parent().parent().attr("id");
            parentsetid = parentsetid.substring(5);
            idx++;
            var songid = $(ui.item).attr("id");
            changeSongOrder(songid, idx);
            var setid = $("#divSetID").html();
            if (parentsetid == setid) {
                reloadSlideOut(parentsetid);
            }
        }
    }).disableSelection();
}
function getListOfSets(userid) {
    var url = "services/wsvc_rwtc_setlist.asmx/getsetlistsbyuser";
    //var url = "handler/getsetlistsbyuser.ashx";
    var values = { "UserID": userid }
    $.ajax({
        type: "POST",
        url: url,
        data: values,
        dataType: "text",
        async: false,
        success: function (data) {
            var setlist;
            setlist = data.split("\n");
            var set;
            $("#lstSelectSetList").empty();

            for (i = 2; i < setlist.length - 1; i++) {
                set = setlist[i].split("\t");
                var $addset;
                $addset = $('<li/>').html('<a href="#" onclick="loadSetList(' + set[0] + ');">' + set[1] + '</a>');
                //$addset = $('<li/>').html(set[1]);
                $($addset).appendTo("#lstSelectSetList");
            }

        },
        error: function (e) {
            alert('sets not loaded' + e);
            return false
        }
    });
}
function fixup(str) {
    if (str != "" && str != null) {
        var strInputCode = str;
        strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1) {
            return (p1 == "lt") ? "<" : ">";
        });
        str = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    }
    if (str == undefined)
        return "";
    var loc;
    loc = str.indexOf("\"");
    while (loc != -1) {
        str = str.replace("\"", "Q1XJG$");
        loc = str.indexOf("\"");
    }
    loc = str.indexOf("Q1XJG$");
    while (loc != -1) {
        str = str.replace("Q1XJG$", "\\\"");
        loc = str.indexOf("Q1XJG$");
    }
    return str;
}
function doLogin() {
    //remove all the class add the messagebox classes and start fading
    $("#saveLogin").fadeOut();
    $(".lblPwdRec").fadeOut();
    var UserName = $(".txtUserName").val();
    var Password = $(".txtPassword").val();
    if (UserName == "") {
        $("#msgbox").removeClass().text("A User Name Is Required").fadeIn(1000);
    }
    else if (Password == "") {
        $("#msgbox").removeClass().text("A Password Is Required").fadeIn(1000);
    }
    else {
        $("#msgbox").removeClass().text('Validating....').fadeIn(1000);
        var chkd = '';
        if ($('#chksaveLogin:checked').val() != null)
            chkd = $('#chksaveLogin:checked').val();

        $.post("login_ajax.aspx", { txtUserName: $('.txtUserName').val(), txtPassword: $('.txtPassword').val(), chksaveLogin: chkd, rand: Math.random() },
            function (data) {
                if (data == '1') //if correct login detail
                {
                    $("#msgbox").fadeTo(200, 0.1, function ()  //start fading the messagebox
                    {
                        //add message and change the class of the box and start fading
                        $(this).html('Logging in.....').fadeTo(900, 1,
                      function () {
                          $(".lblLogin").hide();
                          $(".lblLogout").show();
                          $(".loginImage").slideUp("200");
                          $(".loginButton").slideUp("200");
                          $(".loginTable").addClass("hidden");
                          $("#msgbox").hide();
                          $(".lblMyAccount").show();
                          $(".lblSignUp").hide();
                          $(".slAdd").show();
                          $(".isfav").show();
                          if (!isiPad() && $("#hdnslideout").val() != 'no') {
                              initiateSlideOut();
                          }
                          $("#slideoutwelcome").addClass("hide");
                      });
                    });
                }
                else if (data == '2') //if renew membership agreement
                {
                    $("#msgbox").fadeTo(200, 0.1, function ()  //start fading the messagebox
                    {
                        //add message and change the class of the box and start fading
                        $(this).html('Please Renew Your Membership Agreement').fadeTo(900, 1,
                      function () {
                          window.location = "agreement_update.asp"; //redirect to membership agreement page
                      });
                    });
                }
                else if (data == '3') //if verify e-mail
                {
                    $("#msgbox").fadeTo(200, 0.1, function ()  //start fading the messagebox
                    {
                        //add message and change the class of the box and start fading
                        $(this).html('Please Verify Email Information.').fadeTo(900, 1,
                      function () {
                          window.location = "email_update.asp"; //redirect to e-mail update page
                      });
                    });
                }
                else if (data == '4') { //if needs reactivate membership
                    $("#msgbox").fadeTo(200, 0.1, function () //start fading messagebox
                    {
                        $(this).html('Please Reactivate Your Membership').fadeTo(900, 1,
                       function () {
                           window.location = "profile.asp";
                       });
                    });
                }
                else {
                    $("#msgbox").fadeTo(200, 0.1, function () //start fading the messagebox
                    {
                        //add message and change the class of the box and start fading
                        $(this).html('Invalid UserName or Password').fadeTo(900, 1).fadeTo(1000, 1).fadeTo(200, 0, function () {
                            $("#saveLogin").fadeIn();
                            $(".lblPwdRec").fadeIn();
                        });
                    });
                }
            });
    }
}
function logout() {
    var options = { path: '/', expires: 10 };
    var options2 = { path: '/guitar', expires: 10 };
    var options3 = { path: '/', expires: 10, domain:'.1christian.net' };
    $.cookie('UserID', null, options);
    $.cookie('UserID', null, options2);
    $.cookie('UserID', null, options3);
    $.cookie('userid', null, options);
    $.cookie('userid', null, options2);
    $.cookie('userid', null, options3);
    $.cookie('LoggedIn', null, options);
    $.cookie('LoggedIn', null, options2);
    $.cookie('LoggedIn', null, options3);
    $.cookie('loggedin', null, options);
    $.cookie('loggedin', null, options2);
    $.cookie('loggedin', null, options3);
    $.cookie('Access', null, options);
    $.cookie('Access', null, options2);
    $.cookie('access', null, options);
    $.cookie('access', null, options2);
    $(".lblLogin").show();
    $(".lblLogout").hide();
    $(".lblMyAccount").hide();
    $(".lblSignUp").show();
    window.location = "./"
}
function saveEmail(email, fname, lname, city, state, zip) {
    if (isvalidemail(email)) {
        var url = "services/wsvc_email.asmx/addemail";
        var values = { "email": email, "Firstname":fname,"Lastname":lname,"City":city,"State":state,"Zip":zip }
        $.ajax({
            type: "POST",
            url: url,
            data: values,
            dataType: "text",
            async: false,
            success: function (data) {
                var suc = parseInt(data);
                alert('email saved : ' + data);

            },
            error: function (e) {
                alert('email not saved : ' + e.d);
                return false
            }
        });

    }
    else{
        alert("invalid email : " + email);
    }

}
function showWelcome() {
    $("#slideoutwelcome").removeClass("hide");
    $(".handle").attr("title", "click to slide");

    $('.slideoutwelcome').tabSlideOut({
        tabHandle: '.handle',                     //class of the element that will become your tab
        pathToTabImage: 'img/welcome_tab.png',    //path to the image for the tab //Optionally can be set using css
        imageHeight: '122px',                     //height of tab image           //Optionally can be set using css
        imageWidth: '40px',                       //width of tab image            //Optionally can be set using css
        tabLocation: 'right',                      //side of screen where tab lives, top, right, bottom, or left
        speed: 300,                               //speed of animation
        action: 'click',                          //options: 'click' or 'hover', action to trigger animation
        topPos: '150px',                          //position from the top/ use if tabLocation is left or right
        leftPos: '20px',                          //position from left/ use if tabLocation is bottom or top
        fixedPosition: true                      //options: true makes it stick(fixed position) on scroll
    });
    var ref = document.referrer.toLowerCase();
    ref = ref.substring(ref.indexOf("//") + 2);
    ref = ref.replace("www.", "");
    var dom = ref.substring(0, ref.indexOf("/"));
    var hide = $.cookie("hidesplash");
    if (hide == null) {
        //alert($.browser.msie  + "\n" + $.browser.version);
        $('.slideoutwelcome').animate({ right: '-3px' }, 200).addClass('open');
    }
    $.cookie("hidesplash", "Y", { path: '/' });
}
function showSplash2() {
    var ref = document.referrer.toLowerCase();
    ref = ref.substring(ref.indexOf("//") + 2);
    ref = ref.replace("www.", "");
    var dom = ref.substring(0, ref.indexOf("/"));

    if (dom.indexOf('1christian') == -1) {
        var hide = $.cookie("hidesplash");
        var user = $.cookie("userid");
        if (hide == null && user == null) {
            $("#divwelcome").prettyPhoto({
                modal: false,
                default_width: 600,
                default_height: 490,
                opacity: 0.80
            });
            $.prettyPhoto.open("#divwelcome");
            $.cookie("hidesplash", "Y", { path: '/' });
        }
    }
}
function rollover(obj) { obj.style.cursor = 'pointer'; obj.style.backgroundColor = '#433620'; }
function rollout(obj) { obj.style.backgroundColor = '#332610'; }
function openTab(TabID) { location.href = "show.asp?ID=" + TabID; }
function loginDialog(urlEnd) {
    $('#login-join').dialog({
        modal: true,
        title: 'Login',
        buttons: {
            "Login": function () {
                if ($('#txtUserNameDialog').val() == "" || $('#txtPasswordDialog').val() == "") {
                    alert("Please fill in your login information and then try again.")
                } else {
                    $.post("login_ajax.aspx", { //send UserName and Password to login_ajax.aspx
                        txtUserName: $('#txtUserNameDialog').val(),
                        txtPassword: $('#txtPasswordDialog').val(),
                        saveLogin: $("#checkSaveLogin").val()
                    },
                    function (data) {
                        if (data == 1) /* If Login is Successful*/{
                            $(".lblLogin").hide();
                            $(".lblLogout").show();
                            $(".lblMyAccount").show();
                            $(".lblSignUp").hide(); 
                        }
                        else if (data == '2') /*if renew membership agreement */{
                            alert("Please renew your membership agreement.");
                            window.location = "agreement_update.asp"; //redirect to membership agreement page
                        }
                        else if (data == '3') /*if verify e-mail */{
                            alert("Please confirm that your email information is up-to-date");
                            window.location = "email_update.asp"; //redirect to e-mail update page
                        }
                        else if (data == '4') { //if needs reactivate membership
                            alert("Please reactivate your membership");
                            window.location = "profile.asp";
                        }
                        else /* If the Login failed */{
                            alert("Your login was not successful.  Please try again.")
                        }
                    });
                }
                $(this).dialog('close');
            },
            "Join Now!": function () {
                document.location = "join.asp?redir=" + urlEnd;
            }
        }
    });
}
$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}
function isiPad() {
    return (navigator.userAgent.indexOf("iPad") != -1);
}
function isvalidemail(eml) { 
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

  if (eml == '') {
   return false;
  } else if(!emailReg.test(eml)) {
   return false
  }

  return true;
}
