﻿var isLoggedIn = false;

$(document).ready(function() {
    SecurityService.User(determineLogin, genericAsyncError);
    
  
    handleDefaults();
    
    var crazyLogoShake = false;
    
    //$("#logo").hover(function() {  highlightLogo(false); crazyLogoShake = ! crazyLogoShake; }, function() {});
    
    $('#header-login-form input').keyup(function(e) {
        if(e.keyCode == 13) {
           YukonoDoLogin();
        }
    });
    
    $('#search input').keyup(function(e) {
        if(e.keyCode == 13) {
           YukonoDoSearch();
        }
    });
    
    $("#header-login-email").val($.cookie("YukonoEmail"));
  
    initReviewVoteButtons();
});

function genericAsyncError(error) {
    alert(error);
}   

/* Login / Logout related code */

function determineLogin(result) {

    if (result.length > 0) {
        isLoggedIn = true;
        $("#header-displayname").html("<a href=\"/user/"+result+".aspx\">" + result + "</a>");
        $("#header-logout-link").show();
        $("#header-login-link").hide();
    
        initPage(result);
    }
    else {
        isLoggedIn = false;
        $("#header-displayname").html("");
        $("#header-login-link").show();
        $("#header-logout-link").hide();
        
        initPage("");
    }
}

function ShowLogin() {
    var loginLink = $("#header-login-link");
    var loginForm = $("#header-login-form");
    
    loginForm.css("top", loginLink.offset().top + loginLink.height() + 0);
    loginForm.css("left", loginLink.offset().left - loginForm.width() + loginLink.width() - 18);
    
    maskScreen();
    
    loginForm.show();
    
    if ($("#header-login-email").val() == "")
        $("#header-login-email").focus();
    else 
        $("#header-login-password").focus();
}

function HideLogin() {
    unmaskScreen();
    
    $("#header-login-form").hide();
}

function YukonoDoLogin() {
    $("#header-login-error").text("");

    var email = trim($("#header-login-email").val());
    var password = trim($("#header-login-password").val());
    
    if (trim(email).length == 0) {
        $("#header-login-error").text("Enter your email address and this will work better.");
        return;
    }
    
    if (trim(password).length == 0) {
        $("#header-login-error").text("Enter your password and get this party started!");
        return;
    }
    
    showLoading();
    
    $("#header-login-password").val("");
    
    SecurityService.Login(email, password, YukonoLoginResults, FailedCallback);
}

function FailedCallback(junk) {
    hideLoading();
    
    alert(junk.get_message());
}

function YukonoLoginResults(result) {
    hideLoading();

    if (result == undefined || result.length == 0) {
        $("#header-login-error").text("The combo you entered doesn't match what we've got, try again!");
        $("#header-login-password").val("")
        return;
    }
    
    $.cookie("YukonoEmail", trim($("#header-login-email").val()), {expires: 14});
    
    unmaskScreen();
    
    $("#header-login-form").fadeOut();
    determineLogin(result);
}


function YukonoLogout() {
    SecurityService.Logout(YukonoLogoutComplete, YukonoLogoutComplete);
}

function YukonoLogoutComplete() {
    determineLogin("");
}


/* Search related code */

function GoToSearchPage() {
    var keywords = trim($("#header-search-keywords").val());
    
    if (keywords.length == 0) {
        return false;
    }
    
    document.location = "/Search.aspx?keywords=" + escape(keywords);
}

var timeoutHandle;

function YukonoDoSearchDelay() {
    if (timeoutHandle != null)
        window.clearTimeout(timeoutHandle);

    timeoutHandle = window.setTimeout(YukonoDoSearch, 400);
}

function YukonoDoSearch() {
    timeoutHandle = null;

    var keywords = trim($("#header-search-keywords").val().replace("'", "''"));
    
    if (keywords.length == 0) {
        HideSearchResults();
        return false;
    }
    
    var searchBox = $("#header-search-keywords");
    var resultsPanel = $("#search-results");
    
    resultsPanel.css("left", searchBox.offset().left);
    resultsPanel.css("top", searchBox.offset().top + searchBox.outerHeight());
    resultsPanel.html("<img src='/Images/Loading2.gif'> Loading...");
    resultsPanel.fadeIn("slow");
    
    SearchService.searchForListingDetailed(keywords, ShowSearchResults, YukonoDoSearchFailed);
    
    return false;
}

function HideSearchResults() {
    $("body").unbind("click");
    
    $("#search-results").fadeOut("fast");
}

function YukonoDoSearchFailed(error) {
    alert(error.get_message());
}

function ShowSearchResults(results) {
    var resultsPanel = $("#search-results");
    resultsPanel.empty();

    if (results == "[]") {
        resultsPanel.append("No results match your keywords");
    }
    else {
        var list = eval("(" + results + ")");
        
        for (result in list) {
            var listing = list[result];
            
            if (result == list.length - 1) {
                var item = "<p class=\"last-one\" onclick=\"openListingPage('" + listing.YukonoUrl + "');\">" + listing.Name + "</p>";
            }
            else
                var item = "<p onclick=\"openListingPage('" + listing.YukonoUrl + "');\">" + listing.Name + "</p>";
            
            resultsPanel.append(item);
        }
    }
    
    resultsPanel.children("p").each(function() {
        $(this).hover(function() { $(this).addClass("over"); }, function() { $(this).removeClass("over"); });
    });
    
    
    $("#search-results").bind("click", function(event) {
        return false;
    });

    $("body").bind("click", function(event) {
        HideSearchResults();
    });
}

function openListingPage(listingUrl) {
    document.location = "/" + listingUrl + ".aspx";
}

function maskScreen(showLoader) {
    var box = $("#modalBox");
    box.css("height", $(document).height());
    box.css("width", $(document).width());
    
    box.children().hide();
    box.fadeIn("slow");
    
    if (showLoader)
        showLoading();
}

function showLoading() {
    var box = $("#modalBox");
    
    if (showLoading)
        box.children().fadeIn("fast");
}

function hideLoading() {
    var box = $("#modalBox");
    box.children().fadeOut("fast");
}

function unmaskScreen() {
    var box = $("#modalBox");
    box.fadeOut("slow");
}

function highlightLogo(goCrazy) {
    $("#logo").stop();
    
    wiggleLogo(goCrazy);
    wiggleLogo(goCrazy);
    wiggleLogo(goCrazy);
    wiggleLogo(goCrazy);
    wiggleLogo(goCrazy);
    wiggleLogo(goCrazy);
}
        
function wiggleLogo(goCrazy) {
    if (goCrazy)
        $("#logo").animate({width: "188px", marginLeft: "0px", marginTop: "8px"}, 200).animate({width: "128px", marginLeft: "23px", marginTop: "18px"}, 200);
    else
        $("#logo").animate({width: "138px", marginLeft: "18px", marginTop: "17px"}, 200).animate({width: "128px", marginLeft: "23px", marginTop: "18px"}, 200);
}

function shrinkCategories() {    
    $("#nav_categories").animate({
        height: 250
    }, 700, function() { $("#categoryShowLink").slideDown("slow"); });
}

function growCategories() {
    $("#nav_categories").animate({
        height: 980
    }, 1000, function() { $("#categoryShowLink").fadeOut("fast"); $("#nav_categories").css("height", "auto"); });
}

function toggleShrinkCategories() {
    if ($("#nav_categories").css("height").replace('px','') < 300)
        growCategories();
    else
        shrinkCategories();
}


/*
    make an ajax call to increment the comment count
       ajax call returns new count

    change the thumbs up button to disabled

    increment the display count

    add id to cookie list

*/
function incrementCommentVote(val) {
    var listingId = getVars()["ListId"];
    var addedToCookie = false;
    var expiresInDays = 3652; // approx 10 years from now
    // add it to the cookie list
    // need the listing guid id from the page.
    if (listingId) {
        var userVotedOn = $.cookie(listingId);
        if (userVotedOn) {
            // make sure this hasn't been added so they can't vote again 
            if (userVotedOn.indexOf(val) == -1) {
                // set to expire in 3652 days from now/ approx 10 years 
                $.cookie(listingId, val + "|" + userVotedOn, { expires: expiresInDays });
                addedToCookie = true;
            }
        }
        else {
            // first time the person has voted on the listing
            // set to expire in 3652 days from now/ approx 10 years 
            $.cookie(listingId, val, { expires: expiresInDays });
            addedToCookie = true;
        }
    }

    if (addedToCookie == true) {
        disableVote(val);
        incrementVoteCount(val);
        YukonoIncrementReviewVotes(val);
    }
}

// cheap way of incrementing the count of votes
// the other way would be to get the result of the ajax call
function incrementVoteCount(val) {
    var count = parseInt($("#count_" + val).text());
    
    if (!isNaN(count)) {
        count++;
        $("#count_" + val).text(String(count));
    }
}


/*
 change the comment vote button to an inactive thumbs and disable the associated javascript
*/
function disableVote(val) {
    $("#" + val).attr("src", "Images/inactive_vote.png");
    $("#" + val).attr("onclick", "");
    $("#" + val).attr("alt", "Already voted up");
    $("#" + val).attr("title", "Already voted up");
}


/*
parse the main form for the listing id

get cookie by that name

parse cookie value and disable all vote buttons with matching ids in cookie value

*/
function initReviewVoteButtons() {
    var listingId = getVars()["ListId"];
   
    var userVotedOn = $.cookie(listingId);
    if (userVotedOn) {
        var comments = userVotedOn.split('|');
        for (var i = 0; i < comments.length; i++) {
            disableVote(comments[i]);
        }
    }
}


// get the parameters for the get section of the form if any
function getVars() {
    var action = $("#aspnetForm").attr("action");
    var vars = [], hash;
    var hashes = action.slice(action.indexOf('?') + 1).split('&');

    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
   return vars;
}
