﻿function tab(title, content) {
    jQuery('.' + content).hide(); //Hide all content
    jQuery('#' + title + ' table tbody tr td:first').addClass("selected").show(); //Activate first tab
    jQuery('.' + content + ':first').show(); //Show first tab content

    jQuery('#' + title + ' table tbody tr td a').click(function () {
        jQuery('#' + title + ' table tbody tr td').removeClass("selected"); //Remove any "active" class
        jQuery(this).parent().addClass("selected"); //Add "active" class to selected tab
        jQuery('.' + content).hide(); //Hide all tab content
        var activeTab = jQuery(this).attr("rel"); //Find the rel attribute value to identify the active tab + content
        jQuery('#' + activeTab).fadeIn(); //Fade in the active content
        return false;
    });
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function SendContactForm(type, email, message, itemId, company, name, shouldSetCookie, parentItemId) {
    jQuery.ajax({
        type: "POST",
        url: "/barona/layouts/ajax.aspx/SendContactForm",
        contentType: "application/json; charset=utf-8",
        data: "{type:'" + type + "', email:'" + email + "', message:'" + message + "', itemId:'" + itemId + "', company:'" + company + "', name:'" + name + "', shouldSetCookie:" + shouldSetCookie + ", parentItemId:'" + parentItemId + "'}",
        dataType: "json",
        success: function (msg) {
            var item = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
            jQuery('.contact-form').html(item.Message);
        },
        error: AjaxFailed
    });
}

function AjaxFailed(result) {
    alert('AJAX REQUEST FAILED: ' + result.status + ' ' + result.statusText + ' ' + result.d);
}

function FormValidatorHandler() {
    setTimeout('FormValidatorHandlerTimeOut()', 1);
}
function FormValidatorHandlerTimeOut() {
    var comparedID;
    for (i = 0; i < Page_Validators.length; i++) {
        var inputControl = document.getElementById(Page_Validators[i].controltovalidate);
        if (inputControl != null) {
            var inputID = inputControl.id;
            var inputType = inputControl.type;
            var errorMessage = Page_Validators[i].errormessage;

            var validatorControl = document.getElementById(Page_Validators[i]);

            if (!Page_Validators[i].isvalid) {
                comparedID = inputID;

                if (Page_Validators[i].errormessage != undefined) {
                    //jQuery('.error').append(errorMessage).append(' ');
                }
                switch (inputType) {
                    case 'text':
                        jQuery(validatorControl).css('color', 'green');
                    case 'textarea':
                        jQuery(validatorControl).css('color', 'green');
                }
            }
            // Do not change styles if mentioned control is already flagged as invalid
            else if (inputID != comparedID) {
                switch (inputType) {
                    case 'text':
                        jQuery(inputControl).css('color', '');
                    case 'textarea':
                        //jQuery(inputControl).parent().parent().prev().css('color', ''); 
                }
            }
        }
    }
}


// validators change
jQuery(':text').change(function () {
    FormValidatorHandler();
});
jQuery('textarea').change(function () {
    FormValidatorHandler();
});
jQuery(':checkbox').change(function () {
    FormValidatorHandler();
});
jQuery(':radio').change(function () {
    FormValidatorHandler();
});
jQuery('select').change(function () {
    FormValidatorHandler();
});

// combobox widget (autocomplete with button)
(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var self = this,
					select = this.element.hide(),
					selected = select.children(":selected"),
					value = selected.val() ? selected.text() : "";
            var input = this.input = $("<input>")
					.insertAfter(select)
					.val(value)
					.autocomplete({
					    delay: 0,
					    minLength: 0,
					    source: function (request, response) {
					        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
					        response(select.children("option").map(function () {
					            var text = $(this).text();
					            if (this.value && (!request.term || matcher.test(text)))
					                return {
					                    label: text.replace(
											new RegExp(
												"(?![^&;]+;)(?!<[^<>]*)(" +
												$.ui.autocomplete.escapeRegex(request.term) +
												")(?![^<>]*>)(?![^&;]+;)", "gi"
											), "<strong>$1</strong>"),
					                    value: text,
					                    option: this
					                };
					        }));
					    },
					    select: function (event, ui) {
					        ui.item.option.selected = true;
					        self._trigger("selected", event, {
					            item: ui.item.option
					        });
					    },
					    change: function (event, ui) {
					        if (!ui.item) {
					            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
									valid = false;
					            select.children("option").each(function () {
					                if ($(this).text().match(matcher)) {
					                    this.selected = valid = true;
					                    return false;
					                }
					            });
					            if (!valid) {
					                // remove invalid value, as it didn't match anything
					                $(this).val("");
					                select.val("0");
					                input.data("autocomplete").term = "";
					                return false;
					            }
					        }
					    }
					})
					.addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>")
						.data("item.autocomplete", item)
						.append("<a>" + item.label + "</a>")
						.appendTo(ul);
            };

            this.button = jQuery("<button type='button'>&nbsp;</button>")
					.attr("tabIndex", -1)
					.attr("title", "Show All Items") // needs to be set from a resource instead
					.insertAfter(input)
					.button({
					    icons: {
					        primary: "ui-icon-triangle-1-s"
					    },
					    text: false
					})
					.removeClass("ui-corner-all")
					.addClass("ui-corner-right ui-button-icon")
					.click(function () {
					    // close if already visible
					    if (input.autocomplete("widget").is(":visible")) {
					        input.autocomplete("close");
					        return;
					    }

					    // work around a bug (likely same cause as #5265)
					    $(this).blur();

					    // pass empty string as value to search for, displaying all results
					    input.autocomplete("search", "");
					    input.focus();
					});
        },

        destroy: function () {
            this.input.remove();
            this.button.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);

// datatables sorting implementation
jQuery.fn.dataTableExt.oApi.fnSortNeutral = function (oSettings) {
    if (!(oSettings == null)) {
        /* Remove any current sorting */
        oSettings.aaSorting = [];
        /* Sort display arrays so we get them in numerical order */
        oSettings.aiDisplay.sort(function (x, y) {
            return x - y;
        });
        oSettings.aiDisplayMaster.sort(function (x, y) {
            return x - y;
        });
        /* Redraw */
        oSettings.oApi._fnReDraw(oSettings);
    }
} 
