//Used for Add to favorites functionality
var isFavorite = 1, isNotFavorite = 2;
var addFavorite = "addToFavorites", removeFavorite = "removeFromFavorites";

/* Show floating message after page load */
function showMessage(message) {
    $.jGrowl(message, { corners: '3px' });
}

//Used for login error messages
function openLoginPanel() {

    $("#SigninPanel").overlay(
        { expose: '#000',
            api: true,
            top: 'center',
            onClose: function () {
                $(".loginTextbox").html("");
                $("fieldset#loginControls p.loginError").hide();
                $("fieldset#loginControls p#loginPanelMessage").hide();
            }
        }).load();

}

/* Add to/Remove from favorites */
function toggleFavorite(restaurant, action) {

    var activeLink = $("a." + action + "[rel=" + restaurant + "]");

    $.ajax({
        url: "ToggleFavorites.aspx?Action=" + action + "&Restaurant=" + restaurant,
        type: "POST",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        processData: true,
        dataType: "json",
        timeout: 15000,
        beforeSend: function () {

            //Set 'Please wait' message, and disable link
            $(activeLink).attr("href", "").html("Please wait...");

        },
        error: function (xhr, desc, exceptionobj) {

            $(activeLink).attr("href", "javascript:void(0);");

            //Reset to default state
            if (action == "addToFavorites") {
                $(activeLink).html("Remove from favorites").removeClass().addClass("addToFavorites");
                $.jGrowl("Sorry, there was a problem adding the restaurant to your favorites. Please try again, or refresh the page.", { corners: '3px' });
            }
            else {
                $(activeLink).html("Add to favorites").removeClass().addClass("removeFromFavorites");
                $.jGrowl("Sorry, there was a problem removing the restaurant from your favorites. Please try again, or refresh the page.", { corners: '3px' });
            }

        },
        success: function (data) {

            $(activeLink).attr("href", "javascript:void(0);");

            //Status received from Add to favorites page, and indicates success
            if (data.Result == "Added Successfully") {

                $(activeLink).html("Remove from favorites").removeClass().addClass("removeFromFavorites");

                $("span#numFavorites").html("(favorited by " + data.NumFavorites + " users)");
                $.jGrowl("Restaurant added to favorites", { corners: '3px' });

            }
            else if (data.Result == "Removed Successfully") {

                $(activeLink).html("Add to favorites").removeClass().addClass("addToFavorites");

                $("span#numFavorites").html("(favorited by " + data.NumFavorites + " users)");
                $.jGrowl("Restaurant removed from favorites", { corners: '3px' });

            }
            else {
                //Invalid response? 

                if (data.FinalState == "ShowRemoveFavorite") {
                    $(activeLink).html("Remove from favorites").removeClass().addClass("removeFromFavorites");
                }
                else {
                    $(activeLink).html("Add to favorites").removeClass().addClass("addToFavorites");
                }

                if (action == "removeFromFavorites")
                    $.jGrowl("There was an error removing the restaurant from your favorites: " + data.Result, { corners: '3px' });
                else
                    $.jGrowl("There was an error adding your favorites: " + data.Result, { corners: '3px' });

                $("span#numFavorites").html("(favorited by " + data.NumFavorites + " users)");
            }

        }
    });
    
    return;

}

//loadResults Modes
var GET_ZONES = 1;
var GET_CUISINES = 2;
var RESET = 0;

/* Load cuisines/zones through AJAX when the dropdowns are used */
function loadResults(cuisineText, zoneText, mode) {
    
    $("#restaurantCount").html("");
    $("#restaurantCount").removeClass("hide");
    
    if(isNaN(cuisineText)) cuisineText = 0;
    if(isNaN(zoneText)) zoneText = 0;
        
    var ajaxMode = "";
        
            if(mode == GET_ZONES) {
                ajaxMode = "GetZones";
            }
            else if(mode == GET_CUISINES) {
                ajaxMode = "GetCuisines";
            }

            $.ajax({
                url: "HomeAJAXHandler.ashx?Mode=" + ajaxMode + "&CuisineID=" + cuisineText + "&ZoneID=" + zoneText,
                type: "POST",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                processData: true,
                dataType: "json",
                timeout: 15000,
                beforeSend: function () {
                    $("#loading").removeClass("hide");
                    $("#errorMessage").addClass("hide");
                    $("#foundInfo").addClass("hide");
                },
                error: function (xhr, desc, exceptionobj) {

                    $("#loading").addClass("hide");
                    $("#errorMessage").removeClass("hide");

                    $("#errorMessage").html("There was a problem, sorry! Please try again");

                },
                success: function (data) {

                    $("#loading").addClass("hide");
                    $("#errorMessage").addClass("hide");
                    $("#foundInfo").removeClass("hide");

                    var resultCount, mode;

                    if (ajaxMode == "GetZones") {
                        $("#zoneList").html("");
                    }
                    else if (ajaxMode == "GetCuisines") {
                        $("#cuisineList").html("");
                    }

                    if (!data[0].error) {

                        resultCount = data[0].TotalResults;
                        var totalCols = data[0].Cols;

                        if (ajaxMode == "GetCuisines" && totalCols > 0 && totalCols <= 5)
                            $("#cuisineList").removeClass().addClass("cuisines" + totalCols + "Cols");
                        else if (ajaxMode == "GetZones" && totalCols > 0 && totalCols <= 4)
                            $("#zoneList").removeClass().addClass("zones" + totalCols + "Cols");

                        /* Iterate through results */
                        for (ctr = 0; ctr < data.length; ctr++) {

                            if (ajaxMode == "GetZones") {

                                //Add to dropdown list
                                if (!data[ctr].ListText == '')
                                    $("<li><a href='javascript:void(0);' rel='" + data[ctr].ID + "'>" + data[ctr].ListText + "</a></li>").appendTo("#zoneList");
                                else
                                    $("<li><div>&nbsp;</div></li>").appendTo("#zoneList");
                            }
                            else if (ajaxMode == "GetCuisines") {
                                if (!data[ctr].ListText == '')
                                    $("<li><a href='javascript:void(0);' rel='" + data[ctr].ID + "'>" + data[ctr].ListText + "</a></li>").appendTo("#cuisineList");
                                else
                                    $("<li><div>&nbsp;</div></li>").appendTo("#cuisineList");
                            }
                        }

                        if (ajaxMode == "GetZones")
                            setZoneEvents();
                        else
                            setCuisineEvents();

                        if (ajaxMode == "GetCuisines") {
                            $("#restaurantCount").html("Found <em>" + resultCount + "</em> restaurants in that Zone.");
                            $(".plc input.browseButtonRestaurants").focus();
                        }
                        else if (ajaxMode == "GetZones") {
                            $("#restaurantCount").html("Found <em>" + resultCount + "</em> restaurants with that Cuisine.");
                            $(".plc input.browseButtonRestaurants").focus();
                        }
                        else
                            $("#restaurantCount").html("<em>" + resultCount + "</em> restaurants found. Click Go!");

                    }
                    else {
                        $("#loading").addClass("hide");
                        $("#errorMessage").removeClass("hide");

                        $("#errorMessage").html("There was a problem, sorry! Please try again");
                    }

                }
            });
    
    }

/* Sets the modes for the cuisines dropdown */
function setCuisineEvents() {

    $("ul#cuisineList a").click(
    function(e) {
        
        $("a#cuisineListLink").html($(this).html());
        $("#selectedCuisine").val($(this).attr("rel"));	
        e.preventDefault();
        
        if ($("#selectedZone").val() == "-1") {
            //Only one of the two dropdowns has been selected

            loadResults($("#selectedCuisine").val(), $("#selectedZone").val(), GET_ZONES);
        }
        else {
            //Both have been selected

            //$("#restaurantCount").html("Taking you to the results...please wait...");
            window.location = "Search-Results.aspx?Mode=Browse&Cuisine=" + $(this).attr("rel") +
            "&Zone=" + $("#selectedZone").val();
        }

    }
    );
    
    }

/* Sets the modes for the zones dropdown */
function setZoneEvents() {

    $("ul#zoneList a").click(
    function(e) {
        
        $("a#zoneListLink").html($(this).html());
        $("#selectedZone").val($(this).attr("rel"));
        e.preventDefault();
        
        if ($("#selectedCuisine").val() == "-1") {
            //Only one of the two dropdowns has been selected

            loadResults($("#selectedCuisine").val(), $("#selectedZone").val(), GET_CUISINES);
        }
        else {
            //Both have been selected

            $("#restaurantCount").html("Taking you to the results...please wait...");
            window.location = "Search-Results.aspx?Mode=Browse&Cuisine=" + $("#selectedCuisine").val() +
            "&Zone=" + $(this).attr("rel");
        }

    }
    );

}

function hideBottomBar() {
    $("#bottomBar").removeClass().addClass("collapsed");
    $.mask.close();
}

/* Close currently open form, and open the other one through callBackFunction */
function openNewForm(callbackFunction, mode) {

    $("#bottomBar").expose({
        closeOnClick: true,
        closeOnEsc: true,
        closeSpeed: "fast",
        color: "#000",
        onClose: function () {
            $(".sharingForm").hide("fast");
            $("#bottomBar").removeClass().addClass("collapsed");
        }
    }).removeClass().addClass("expanded");

    $(".sharingForm").hide();
    callbackFunction();

}

//Fix IE9 bug with FB
$(function () {
    setTimeout(function () {
        if (typeof __flash__removeCallback != "undefined") {
            __flash__removeCallback = __flash__removeCallback__replace;
        } else {
            setTimeout(arguments.callee, 50);
        }
    }, 50);
});

/* Page load events */
$(document).ready(function () {

    if (showLoginPanel) openLoginPanel();

    var searchTextbox = $("input.searchBoxRestaurants");

    $(searchTextbox).focus(
                     function () {
                         if ($(searchTextbox).val() == "Enter a restaurant name, location or cuisine")
                             $(searchTextbox).val("");
                     }
                         );
    $(searchTextbox).blur(
                    function () {
                        if ($(searchTextbox).val() == "")
                            $(searchTextbox).val("Enter a restaurant name, location or cuisine");
                    }
                    );

    setCuisineEvents();
    setZoneEvents();

    $("a#cuisineListLink").click(function () {

        var listPosition = $(this).offset();

        var api = $("a#cuisineListLink").overlay({ api: true, close: 'div.close', top: listPosition.top + 26, left: listPosition.left, onLoad: function () { $(document).click(function () { api.close(); }); },
            onClose: function () { $(document).unbind("click"); }
        }).load();

        $("#cuisineList").css("position", "absolute");

    });

    $("a#zoneListLink").click(function () {

        var listPosition = $(this).offset();

        var api = $("a#zoneListLink").overlay({ api: true, close: 'div.close', top: listPosition.top + 26, left: listPosition.left, onLoad: function () { $(document).click(function () { api.close(); }); },
            onClose: function () { $(document).unbind("click"); }
        }).load();

        $("#zoneList").css("position", "absolute");

    });

    $("a.addToFavorites, a.removeFromFavorites").not(".loginRequiredLinks").click(function (e) {

        var action;

        //Used because the link might have other classes too
        if ($(this).hasClass("addToFavorites"))
            action = "addToFavorites";
        else
            action = "removeFromFavorites";

        e.preventDefault();
        toggleFavorite($(this).attr("rel"), action);

    });

    var whyJoinOverlay = $("a.whyJoin[rel]").overlay({
        top: 'center',
        api: true,
        mask: {
            color: "#000",
            loadSpeed: 0,
            closeSpeed: 0, //this is REQUIRED for the next overlay to work
            opacity: 0.9
        }
    });

    $("a#ratingsPolicy[rel]").overlay({ expose: '#000', top: 'center' });

    $("div.favoriteSection a").click(function (e) { activeLink = $(this).attr("id"); });

    //Green jquery tooltips
    $('img[title], .tooltipLink').tooltip({
        position: 'top center',
        effect: 'slide'
    });

    $("#menuThumbnails a img").tooltip({
        position: 'bottom center',
        effect: 'slide'
    });

    /*
    Characters Remaining Countdown
    */

    if ($(".messageTextbox").length > 0) {

        $(".messageTextbox").each(function (index) {
            $(this).textlimit('div.remaining[rel=' + $(this).attr('id') + ']', 1000);
        });

    }

    if ($(".longMessageTextbox").length > 0) {

        $(".longMessageTextbox").each(function (index) {
            $(this).textlimit('div.remaining[rel=' + $(this).attr('id') + ']', 3000);
        });

    }

    //View user comments
    $("a#viewComments").click(function () {
        $.scrollTo('#commentsSection', 1000);
    });

    //Code to show the sign in panel on clicking a link that requires signing in
    if ($.browser.msie && $.browser.version == "6.0") {
        $("a.loginRequiredLinks").attr("href", "Login.aspx");
    }
    else {

        $("a.loginRequiredLinks[rel]").overlay({
            expose: '#000',
            top: 'center',
            onLoad: function () {
                $("div#loginControls p#loginPanelMessage").html("Sign up in under 2 minutes to get access to member features!").show("fast");
            },
            onBeforeClose: function () {
                $("div#loginControls p#loginPanelMessage").hide("fast");
            }
        });

    }

    var loginLinks = $("a.loginLinks[rel]").overlay({ expose: '#000', top: 'center', api: true });

    //Code to show the sign in panel on clicking the 'sign in' link (clear login error first)
    if ($.browser.msie && $.browser.version == "6.0") {
        $("a.loginLinks").attr("href", "Login.aspx");
    }
    else {

        $("a.loginLinks[rel]").click(function () {

            $("fieldset#gdLogin p.loginError").hide();

        });

        $("fieldset#loginControls .close").click(function () {
            $("#SigninPanel").hide("fast");
        });

    }

    $("a.avatarLink[rel]").overlay({ expose: '#000', top: 'center' });

    //Enables the clear-on-focus and gray text functionality
    $(".swapValue").each(function (i) {

        formHintText[formHintText.length] = $(this).attr("title");

        if ($(this).val() != formHintText[i]) $(this).removeClass("hintText");

        $(this).focus(function () {
            if ($(this).val() == formHintText[i]) {
                $(this).val("");
                $(this).removeClass("hintText");
            }
        }).blur(function () {
            if ($.trim($(this).val()) == "") {
                $(this).val(formHintText[i]);
                $(this).addClass("hintText");
            }
        });
    });

    $("#header .plc #login div#loginControls #singleSignOn div a").click(function () {
        $(this).attr("class", "loading");
    });

    $("#ShowBrowseSearchHyperLink").click(function (e) {
        $(this).hide("fast", function () { $("#search .plc").show("fast"); });
    });

    /* Preload images and other assets */
    preload(['http://c1407072.cdn.cloudfiles.rackspacecloud.com/Images/lightbox-ico-loading.gif']);

    $("#bottomBar #shareEmail input.sendButton").click(function () {

        var controls = $("#shareEmail input.defaultText");

        var controlString = "";

        $(controls).each(function (i, e) {
            controlString += $(this).attr("id") + "=" + $(this).val() + "&";
        });

        controlString = controlString.substr(0, controlString.length - 1);

        $.ajax({
            url: "EmailFriendHandler.ashx?" + controlString,
            type: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            processData: true,
            dataType: "json",
            timeout: 15000,
            beforeSend: function () {
                $("input.sendButton").hide();
                $("div#status").html("Sending...Please wait...");
            },
            success: function (data) {

                if (data.Result == "Success") {
                    $("input.sendButton").show();
                    $("div#status").html("");
                    showMessage("Message sent successfully!");
                    hideBottomBar();
                }
                else if (data.Result == "Failure") {
                    $("div#status").html("<div class='error'>" + data.ErrorMessage + "</div>");
                    $("input.sendButton").show();
                }
                else {
                    $("div#status").html("<div class='error'>Sorry, there was an unknown error. Please try again later.</div>");
                }
            }
        });

    });
    $("#bottomBar #shareEmail input").keypress(function (e) {
        if (e.which == '13') {
            e.preventDefault();
            $("#bottomBar #shareEmail input.sendButton").click();
        }
    });

    /* Set up shareEmail Form */
    $("#showEmailForm").click(function () {
        openNewForm(function () { $("#shareEmail").show("fast", function () { $(".nameTextbox").focus(); }); }, 'shareEmail');
    });

    /* Set up shareTwitter Form */
    $("div.twitter a#showTwitterForm").click(function () {

        openNewForm(function () {

            $("#tweetBox strong").show();

            $("#shareTwitter").show("fast", function () {

                if ($("#tweetBox iframe").length <= 0) {

                    twttr.anywhere(function (T) {

                        T("#tweetBox").tweetBox({
                            height: 100,
                            width: 900,
                            label: "",
                            defaultContent: "Here's another eating out option in Doha:" + window.location + " #gulfdine #doha",
                            onTweet: function (plaintext, html) {
                                hideBottomBar();
                                $.jGrowl("Message tweeted successfully", { corners: '3px' });
                            }
                        });

                        $("#tweetBox strong").hide();

                    });
                }
                else {
                    $("#tweetBox iframe").show("fast", function () { $("#tweetBox strong").hide(); });
                }

            });

        }, 'shareTwitter');

    });

    function __flash__removeCallback__replace(instance, name) {
        if (instance != null)
            instance[name] = null;
    }

    //Load FB asynchronously
    window.fbAsyncInit = function () {

        //var curLoc = window.location;

        FB.init({
            appId: facebookAppId,
            status: true,
            cookie: true,
            xfbml: true,
            channelUrl: "http://beta.gulfdine.com/channel.html"
        });

        FB.Event.subscribe('edge.create', function (response) {
            openNewForm(function () {
                $("#shareFacebook").show("fast");
            }, 'shareFacebook');
        });


    };
    (function () {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = 'http://connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
        } ());

    $("#emailClose, #bottomBar a.close").click(function () {
        $("#shareEmail").hide("fast", function () { hideBottomBar(); });
    });

    $("#facebookClose, #bottomBar a.close").click(function () {
        $("#shareFacebook").hide("fast", function () { hideBottomBar(); });
    });
    $("#twitterClose, #bottomBar a.close").click(function () {
        $("#shareTwitter").hide("fast", function () { hideBottomBar(); });
    });

});
