﻿/// <reference path="jquery.form.js" />

window.bloo =
{
    characterDialog: '#characterDialog',
    collectionCharacterId: '#character-details-collection-dialog #CharacterId',
    collectionDialog: '#character-details-collection-dialog',
    collectionForm: '#character-details-collection-dialog #collection-form',
    customCharacterDialog: '#customCharacterDialog'
};

$(document).ready(function () {
    $('#nav').droppy();
    $.blockUI.defaults.baseZ = 2000;
    $.tablesorter.defaults.widgets = ['zebra'];
    $.tablesorter.defaults.cssAsc = 'sort asc';
    $.tablesorter.defaults.cssDesc = 'sort desc';

    var d = new Date();
    var offset = d.getTimezoneOffset();

    $('.local').each(function () {
        $(this).html(LocalDate($(this).text(), offset));
    });

    $('.localdate').each(function () {
        $(this).html(LocalDate($(this).text(), offset, 1));
    });

    $('table.autosort').tablesorter();

    $('table.striped > tbody > tr:odd').addClass('odd');

    //    $(document).ajaxError(function (e, xhr, settings, exception)
    //    {
    //        var err = $.parseJSON(xhr.responseText);
    //        $.growlUI(null, err.message, 5000);
    //    });

    $(document).ajaxStart(function () {
        $('body').css('cursor', 'wait');
        $('#loading').show();
    });

    $(document).ajaxStop(function () {
        $('body').css('cursor', 'auto');
        $('#loading').hide();
    });

    $(bloo.characterDialog).dialog({
        autoOpen: false,
        modal: true,
        width: 1054
    });

    $(bloo.customCharacterDialog).dialog({
        autoOpen: false,
        modal: true,
        width: 1054
    });

    $(bloo.collectionDialog).dialog(
            {
                autoOpen: false,
                modal: true,
                width: 986,
                title: 'Edit My Collection',
                buttons:
                {
                    Save: function () {
                        var $this = $(this);
                        var data = $this.find('form').serialize();

                        $.post(updateCharacterHaveWantTradeURL, data, function () {
                            $this.dialog('close');

                            var characterId = $(bloo.collectionCharacterId).val();

                            if ($(bloo.characterDialog).is(':visible')) {
                                Character(characterId);
                            }
                            else {
                                LoadDetails(characterId);
                            }
                        });
                    },
                    Cancel: function () { $(this).dialog('close'); }
                }
            });

    //$('textarea[maxLength]').live('keyup keydown focus input paste', LimitTextArea);
});

//function LimitTextArea()
//{
//    var textArea = $(this),
//        maxLength = parseInt(textArea.attr('maxLength')),
//        value = textArea.val(),
//        length = value.length,
//        id = textArea.attr('id')
//        label = textArea.siblings('#' + id + '-chars');

//    if (length > maxLength)
//    {
//        textArea.val(value.substr(0, maxLength));
//        length = maxLength;
//    }

//    var remaining = maxLength - length;

//    label.text('Characters remaining: ' + remaining);
//}

function Character(characterId) {
    $.ajax({
        type: 'GET',
        url: getCharacterDetailsURL(characterId),
        success: function (results) {
            $(bloo.characterDialog).html(results).dialog('open');
        }
    });
}

function CustomCharacter(id) {
    $.ajax({
        type: 'GET',
        url: getCustomCharacterDetailsURL(id),
        success: function (results) {
            var $results = $(results).fixDates();
            $(bloo.customCharacterDialog).html($results).dialog('open');
        }
    });
}

function EditHaveWantTrade(characterId) {
    var $dialog = $(bloo.collectionDialog);

    $.ajax({
        type: 'GET',
        cache: false,
        url: getCharacterCollectionDialogURL,
        success: function (results) {
            $dialog.html(results).dialog('open');
        }
    });

    //    $(bloo.collectionDialog).dialog(
    //            {
    //                autoOpen: true,
    //                modal: true,
    //                width: 986,
    //                title: 'Edit My Collection',
    //                buttons:
    //                {
    //                    Save: function () {
    //                        var $this = $(this);
    //                        var data = $this.find('form').serialize();

    //                        $.post(updateCharacterHaveWantTradeURL, data, function () {
    //                            $this.dialog('close');

    //                            if ($(bloo.characterDialog).is(':visible'))
    //                            {
    //                                Character(characterId);
    //                            }
    //                            else
    //                            {
    //                                LoadDetails(characterId);
    //                            }
    //                        });
    //                    },
    //                    Cancel: function () { $(this).dialog('close'); }
    //                }
    //            }).show();
}

function Unformat(str) {
    return str.replace(new RegExp('\\[', 'g'), '')
              .replace(new RegExp('\\]', 'g'), '')
              .replace(new RegExp('\\{', 'g'), '')
              .replace(new RegExp('\\}', 'g'), '')
              .replace(new RegExp('\\^', 'g'), '');
}

function LocalDate(date, offset, justDate) {
    var d2 = new Date(date);
    d2.setMinutes(d2.getMinutes() - offset);
    var m = d2.getMonth() + 1;
    var d = d2.getDate();
    var y = d2.getFullYear();

    if (justDate) {
        return m + '/' + d + '/' + y;
    }

    var hours = d2.getHours();
    var minutes = d2.getMinutes();

    if (minutes < 10) {
        minutes = '0' + minutes;
    }

    var ampm = 'AM';

    if (hours > 12) {
        hours = hours - 12;
        ampm = 'PM';
    }
    else if (hours == 0) {
        hours = 12;
    }

    return m + '/' + d + '/' + y + ' ' + hours + ':' + minutes + ' ' + ampm;
}

jQuery.getNoCache = function (url, data, callback, type) {
    ///	<summary>
    ///		Loads a remote page using an HTTP GET request.
    ///	</summary>
    ///	<param name="url" type="String">The URL of the HTML page to load.</param>
    ///	<param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
    ///	<param name="callback" optional="true" type="Function">The function called when the AJAX request is complete.  It should map function(responseText, textStatus) such that this maps the options for this AJAX request.</param>
    ///	<param name="type" optional="true" type="String">Type of data to be returned to callback function.  Valid valiues are xml, html, script, json, text, _default.</param>
    ///	<returns type="XMLHttpRequest" />

    // shift arguments if data argument was omited
    if (jQuery.isFunction(data)) {
        type = type || callback;
        callback = data;
        data = null;
    }

    return jQuery.ajax({
        type: 'GET',
        cache: false,
        url: url,
        data: data,
        success: callback,
        dataType: type
    });
};

//jQuery.fn.loadNoCache = function (url, data, callback)
//{
//    ///	<summary>
//    ///		Loads HTML from a remote file and injects it into the DOM.  By default performs a GET request, but if parameters are included
//    ///		then a POST will be performed.
//    ///	</summary>
//    ///	<param name="url" type="String">The URL of the HTML page to load.</param>
//    ///	<param name="data" optional="true" type="Map">Key/value pairs that will be sent to the server.</param>
//    ///	<param name="callback" optional="true" type="Function">The function called when the AJAX request is complete.  It should map function(responseText, textStatus, XMLHttpRequest) such that this maps the injected DOM element.</param>
//    ///	<returns type="jQuery" />

//    if (!this.length)
//    {
//        return this;
//    }

//    var off = url.indexOf(" ");
//    if (off >= 0)
//    {
//        var selector = url.slice(off, url.length);
//        url = url.slice(0, off);
//    }

//    // If the second parameter was provided
//    if (params)
//    {
//        // If it's a function
//        if (jQuery.isFunction(params))
//        {
//            // We assume that it's the callback
//            callback = params;
//            params = null;

//            // Otherwise, build a param string
//        } else if (typeof params === "object")
//        {
//            params = jQuery.param(params, jQuery.ajaxSettings.traditional);
//        }
//    }

//    var self = this;

//    // Request the remote document
//    jQuery.ajax({
//        url: url,
//        type: 'GET',
//        cache: false,
//        dataType: "html",
//        data: params,
//        complete: function (res, status)
//        {
//            // If successful, inject the HTML into all the matched elements
//            if (status === "success" || status === "notmodified")
//            {
//                // See if a selector was specified
//                self.html(selector ?
//                // Create a dummy div to hold the results
//						jQuery("<div />")
//                // inject the contents of the document in, removing the scripts
//                // to avoid any 'Permission Denied' errors in IE
//							.append(res.responseText.replace(rscript, ""))

//                // Locate the specified elements
//							.find(selector) :

//                // If not, just inject the full result
//						res.responseText);
//            }

//            if (callback)
//            {
//                self.each(callback, [res.responseText, status, res]);
//            }
//        }
//    });

//    return this;
//};

jQuery.fn.fixDates = function () {
    var d = new Date(),
		offset = d.getTimezoneOffset(),
		$this = $(this);

    //    $this.children('.local').html(LocalDate($(this).text(), offset));
    //    $this.children('.localdate').html(LocalDate($(this).text(), offset, 1));

    $(".local", $this).each(function () {
        $(this).html(LocalDate($(this).text(), offset));
    });

    $(".localdate", $this).each(function () {
        $(this).html(LocalDate($(this).text(), offset, 1));
    });

    return $this;
};

jQuery.fn.fixTable = function () {
    var $this = $(this);
    $('table.autosort', $this).tablesorter();

    $('table.striped > tbody > tr:odd', $this).addClass('odd');

    return $this;
}

jQuery.fn.decrementDropDown = function (callback) {
    var $options = this.children('option'),
		index = this.children('option:selected').index();

    index--;
    if (index < 0) {
        index = $options.size() - 1;
    }

    $options.removeAttr('selected');
    $options.eq(index).attr('selected', 'selected');

    callback();
};

jQuery.fn.incrementDropDown = function (callback) {
    var $options = this.children('option'),
		index = this.children('option:selected').index(),
		size = $options.size();

    index++;
    if (index >= size) {
        index = 0;
    }

    $options.removeAttr('selected');
    $options.eq(index).attr('selected', 'selected');

    callback();
};

jQuery.fn.defaultButton = function (selector) {
    ///	<summary>
    ///		1: defaultButton() - Triggers the click event of the first child submit button when the Enter key is pressed in a matched element.
    ///     2: defaultButton(selector) - Triggers the click event of the specified button when the Enter key is pressed in a matched element.
    ///     3: defaultButton(fn) - Binds a function to pressing the Enter key of each matched element.
    ///	</summary>
    ///	<param name="selector" type="String">
    ///		2: selector - A CSS selector used to match the default button.
    ///     3: fn - The function to execute.
    ///	</param>
    ///	<returns type="jQuery" />

    if (!selector) {
        jQuery('button:first', this).css('border-width', '2px');
    }
    else if (typeof selector === 'string') {
        jQuery(selector, this).css('border-width', '2px');
    }

    jQuery(this).keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            if (!selector) {
                jQuery('button:first', this).click().focus();
            }
            else if (typeof selector === 'string') {
                jQuery(selector, this).click().focus();
            }
            else if (typeof selector === 'function') {
                selector();
            }

            return false;
        }
        else {
            return true;
        }
    });

    return this;
};
