﻿var ajaxIsLoading = false;
var ajax = {

    defaultContainer: "#ajaxContent",
    init: function()
    {

        //attach hooks to ajax links	
        var ajaxLinks = jQuery("a.ajax");

        //do the links already have this event?
        ajaxLinks.unbind("click", ajax.ajaxClick);
        ajaxLinks.bind("click", ajax.ajaxClick);

        var ajaxFormLinks = jQuery("a.ajaxSubmitLink");
        ajaxFormLinks.unbind("click", ajax.ajaxSubmitLinkClick);
        ajaxFormLinks.bind("click", ajax.ajaxSubmitLinkClick);

        //attach hooks to ajax forms
        var ajaxForm = jQuery("form.ajax");

        ajaxForm.unbind("submit", ajax.ajaxFormSubmit);
        ajaxForm.bind("submit", ajax.ajaxFormSubmit);

        $(".scrollToTop").not(".ajax").unbind("click");
        $(".scrollToTop").not(".ajax").click(function()
        {
            scrollToValue(0);
        });

        $(".scrollToContent").not(".ajax").unbind("click");
        $(".scrollToContent").not(".ajax").click(function()
        {
            scrollToValue(646);
        });

        $("a.popup").not(".ajax").unbind("click");
        $("a.popup").not(".ajax").click(function(e)
        {
            if (e.preventDefault)
            {
                e.preventDefault();
            }
            var popupUrl = $(this).attr("href")
            if (popupUrl.indexOf("?") >= 0)
            {
                popupUrl += "&popup=1";
            }
            else
            {
                popupUrl += "?popup=1";
            }
            loadPopupPage(popupUrl);
        });

        clearInputs();
    },

    ajaxSubmitLinkClick: function(e)
    {
        var form = $(this).parent('form');
        form.submit();
    },

    ajaxClick: function(e)
    {
        aTag = jQuery(this);

        relTarget = aTag.attr("rel");

        if (relTarget == null || relTarget == "")
        {
            relTarget = ajax.defaultContainer;
        }

        if (jQuery(relTarget).length >= 1)
        {
            //Now that we have checked all the necessary details, prevent the default click action
            if (e.preventDefault)
            {
                e.preventDefault();
            }

            if (!ajaxIsLoading)
            {
                ajaxIsLoading = true;

                var hash = aTag.attr("href");
                hash = hash.replace(/^.*#/, '');

                //This code below is to fix the url in IE7. IE7 for some strange reason doesn't strip out the protocol and hostname from the hash url.
                hash = hash.replace("http://", "").replace("https://", "");
                var pathIndex = hash.indexOf("/");
                if (pathIndex >= 0)
                {
                    hash = hash.substring(pathIndex);
                }

                //We need to unescape it so that it doesn't screw up the history plugin if any of the urls have escaped characters in them (e.g. %20).
                hash = unescape(hash);

                closeClassicGame();

                if (aTag.hasClass("scrollToTop"))
                {
                    scrollToValue(0, function()
                    {
                        jQuery.history.load(hash, relTarget);
                    });
                }
                else if (aTag.hasClass("scrollToContent"))
                {
                    scrollToValue(626, function()
                    {
                        jQuery.history.load(hash, relTarget);
                    });
                }
                else
                {
                    jQuery.history.load(hash, relTarget);
                }
            }
        }
    },

    loadUrl: function(urlToLoad, rel)
    {
        var url = "";
        if (urlToLoad && urlToLoad.length > 0)
        {
            url = urlToLoad;

            //Now since we are in javascript land, add the js=1 querystring parameter so that only the main content of the page is returned.
            if (url.indexOf("?") >= 0)
            {
                url += "&js=1";
            }
            else
            {
                url += "?js=1";
            }
        }
        else
        {
            return;
        }

        //Default the container, if one not specified
        var targetContainer = "";
        if (rel)
        {
            targetContainer = rel;
        }
        else
        {
            targetContainer = ajax.defaultContainer;
        }

        //Insert the loading panel into the target container
        var parentElement = jQuery(targetContainer).parent();
        var parentHeight = parentElement.height() + "px";
        parentElement.append("<div class='trans' style='padding-top:" + ((parentElement.height() / 2) - 50) + "px;'><p align='center'><img src='/images/elements/ajax-loader.gif' align='center' /></p></div>");
        jQuery("div.trans").css("height", parentHeight);
        jQuery("div.trans").animate({ opacity: 1 }, 300, function()
        {
            //Do the ajax stuff
            jQuery.ajax({
                type: "GET",
                url: url,
                cache: false,
                async: true,
                success: function(o)
                {
                    jQuery(targetContainer).html(o);

                    //Reinitialize the link event handlers and cufon, etc.
                    ajax.init();

                    Cufon.refresh();

                    //if($.browser.msie && $.browser.version=="6.0") {
                    //	DD_belatedPNG.fix('img.pngFix');
                    //	alert("fail1");
                    //}

                    jQuery("div.trans").animate({ opacity: 0 }, 400, function()
                    {
                        jQuery(this).remove();

                        //Page has fully loaded, let send some tracking info to Google!
                        gaTrackPageView(urlToLoad);
                    });
                },
                error: function(o)
                {
                    //Fade out the contents of the container, set the new contents and then fade back in
                    jQuery(targetContainer).html("<div class='content'><h2>Oops!</h2><p>We were unable to find that page. Please check the URL and try again.</p></div>");

                    //Reinitialize the link event handlers and cufon, etc.
                    ajax.init();

                    Cufon.refresh();

                    //if($.browser.msie && $.browser.version=="6.0") {
                    //	DD_belatedPNG.fix('img.pngFix');
                    //	alert("fail2");
                    //}


                    jQuery("div.trans").animate({ opacity: 0 }, 400, function()
                    {
                        jQuery(this).remove();
                    });
                },
                complete: function(xhr, textStatus)
                {
                    ajaxIsLoading = false;
                }
            });
        });
    },

    ajaxFormSubmit: function()
    {

        if ($(this).hasClass('novalidation'))
        {
            // dont do any validation
        }
        else
        {
            try
            {
                if ($(this).validate() == false)
                    return false;
            }
            catch (err)
            {
            }
        }

        // now we're going to capture *all* the fields in the
        // form and submit it via ajax.

        objForm = jQuery(this);
        submitButton = jQuery(this).find("input[type=submit]");
        //otherInputs = jQuery(this).find("input[type=button],input[type=image]");
        allInputs = jQuery(this).find("input");
        allInputs.attr("disabled", "disabled");
        jQuery("span#submitLoadingIcon").remove();
        submitButton.after("<span id='submitLoadingIcon'><img src='/images/elements/ajax-loader.gif' /></span>");
        //submitButton.fadeOut("fast", function() { jQuery("div.loading").fadeIn("fast"); });

        // :input is a macro that grabs all input types, select boxes
        // textarea, etc.  Then I'm using the context of the form from 
        // the initial '#contactForm' to narrow down our selector
        var inputs = [];
        $(':input', this).not('input[type=hidden]').not(':checkbox').not(':radio').each(function()
        {
            inputs.push(this.name + '=' + escape(this.value));
        });

        $(':checked', this).not(':radio').each(function()
        {
            inputs.push(this.name + '=' + escape("True"));
        });
        $(':checked', this).not(':checkbox').each(function()
        {
            inputs.push(this.name + '=' + escape(this.value));
        });

        $('input[type=hidden]', this).each(function()
        {
            inputs.push(this.name + '=' + escape(this.value));
        });

        //console.log('submit 2');
        // now if I join our inputs using '&' we'll have a query string
        jQuery.ajax({
            type: "POST",
            data: inputs.join('&'),
            url: this.action,
            cache: false,
            async: true,
            timeout: 10000,
            error: function()
            {
                jQuery("span#submitLoadingIcon").remove();
                allInputs.removeAttr("disabled");
                infoOverlay("Sorry, we could not submit the form. Please try again later.");
            },
            success: function(o)
            {
                jQuery("span#submitLoadingIcon").remove();
                allInputs.removeAttr("disabled");
                var responseXml = $(o);
                var statusCode = $("status", responseXml).text();
                if (statusCode == "1")
                {
                    var responseData = $("data", responseXml);
                    var messageObj = $("message", responseData);
                    var message = messageObj.text().replace(/&lt;/g, "<").replace(/&gt;/g, ">");
                    var redirect = messageObj.attr("redirect");

                    var callback = $("callback", responseData);
                    if (callback != null)
                        eval(callback.text());

                    infoOverlay(message, true);
                    if (redirect != null)
                    {
                        if (redirect == ".")
                        {
                            refreshAjaxPage();
                        }
                        else
                        {
                            redirect = unescape(redirect);
                            jQuery.history.load(redirect, ajax.defaultContainer);
                        }
                    }
                    else
                    {
                        $(":input", objForm)
                         .not(":button, :submit, :reset, :hidden")
                         .val("")
                         .removeAttr("checked")
                         .removeAttr("selected");
                    }
                }
                else
                {
                    var errorMessage = "";
                    var errorList = $("error", o);
                    errorList.each(function()
                    {
                        errorMessage += $(this).text().replace(/&lt;/g, "<").replace(/&gt;/g, ">") + "\n";
                    });
                    infoOverlay(errorMessage);
                }
            }
        });

        // by default - we'll always return false so it doesn't redirect the user.
        return false;
    },

    ajaxClickWithCallback: function(url, beforeSendCallback, successCallback, errorCallback, sender, data)
    {
        var reqType = "GET";
        if (data)
        {
            reqType = "POST";
        }
        jQuery.ajax({
            type: reqType,
            url: url,
            data: data,
            cache: false,
            async: true,
            beforeSend: function(xhr)
            {
                return beforeSendCallback(xhr, sender);
            },
            success: function(data, status, xhr)
            {
                successCallback(data, status, xhr, sender);
            },
            error: function(xhr, status, errorThrown)
            {
                errorCallback(xhr, status, errorThrown, sender);
            }
        });

        return false;
    }
}
jQuery(document).ready(ajax.init);
jQuery(document).ready(function(){
    // Initialize history plugin.
	// The callback is called at once by present location.hash. 
	jQuery.history.init(ajax.loadUrl);
	
});
