/**
 *	Listers Group Website
 *	Javascript
 */

//	These variables are needed for functions on this page
var openModal;

//	This is all done AS the page loads - no need to wait for the DOM to be ready for this
//	Add a class to the HTML element of the page to aid the styling of the site
var thisBrowser = "Unknown";
if ($.browser.msie) {
	thisBrowser = "IE";
}
if ($.browser.safari) {
	thisBrowser = "Webkit";
}
if ($.browser.opera) {
	thisBrowser = "Opera";
}
if ($.browser.mozilla) {
	thisBrowser = "Mozilla";
}

$("html").addClass("is" + thisBrowser);
$("html").addClass("is" + thisBrowser + parseInt($.browser.version));
if ($.browser.mozilla) $("html").addClass("is" + thisBrowser + parseFloat($.browser.version.replace(/\.\d$/, "").replace(/\./g, "")));
$("html").addClass("is" + thisBrowser + parseFloat($.browser.version.replace(/\./g, "")));

if (navigator.userAgent.toLowerCase().search(/iphone|ipod|ipad|android/g) > -1) $("html").addClass("isMobileWebkit");
if (navigator.userAgent.toLowerCase().search(/chrome|chromium/g) > -1) $("html").addClass("isChrome");

//	The following functions are all done once the DOM is ready
$(function () {

    // QuickSearch
    if ($("#QuickSearchWrap").length > 0) {

        $("#QuickSearchWrap .QuickSearchType").hide();
        $("#" + $(".QuickSearch_Type")[0].value).show();

        $(".QuickSearch_Type").change(function (e) {
            $("#QuickSearchWrap .QuickSearchType:visible").fadeOut(250, function () {
                $("#" + $(".QuickSearch_Type")[0].value).fadeIn(250);
            });
        });
    }

    // Allow a checkbox to control the visibilty of other form items (checked box -> visible item)
    if ($(".VisibilityController").length > 0) {
        $(".VisibilityController input").click(function () {
            var ControlledClass = findClass($(this).parents(".VisibilityController"), "Controls-");
            if (ControlledClass == "") ControlledClass = "Controlled";
            if ($(this).get(0).checked) {
                $("." + ControlledClass).show();
            } else {
                $("." + ControlledClass).hide();
            }
        });
        $(".VisibilityController input").each(function () {
            var ControlledClass = findClass($(this).parents(".VisibilityController"), "Controls-");
            if (ControlledClass == "") ControlledClass = "Controlled";
            if ($(this).get(0).checked) {
                $("." + ControlledClass).show();
            } else {
                $("." + ControlledClass).hide();
            }
        });
    }
    // Tabs
    /*	$tabPages = $(".TabsSameHeight .TabPage")
    var tabs_maxTabHeight = 0;
    $tabPages.each(function() {
    if ($(this).height() > tabs_maxTabHeight) tabs_maxTabHeight = $(this).height();
    }).each(function() {
    $(this).css("min-height", tabs_maxTabHeight + "px");
    }); */

    // Make all the tabs and their wrapper DIVs the same height, to prevent the page height from changing
    $(".TabsSameHeight").each(
			function (i) {

			    if ($(this).hasClass("UniformTabs")) $(this).tabs();

			    var maxHeight = $(this).outerHeight();
			    var realMaxHeight = maxHeight;

			    $(this).children(".TabSections").children(".Tab").each(
					function (j) {
					    actualOuterHeight = $(this).outerHeight() + parseInt($(this).css("margin-top")) + parseInt($(this).css("margin-bottom")) + 10;
					    if (actualOuterHeight > maxHeight) {
					        realMaxHeight = $(this).outerHeight();
					        maxHeight = actualOuterHeight;
					    }
					}
				);

			    $(this).children(".TabSections").children(".Tab").height(realMaxHeight);
			    $(this).children(".TabLinks").height(realMaxHeight);
			    $(this).height(
					maxHeight +
					parseInt($(this).css("padding-top")) +
					parseInt($(this).css("padding-bottom")) - 1
				);

			}
		);

    $(".Tabs").tabs();
    $(".TabContainer").tabs();

    // Loop through each link on the page that has a class of 'TabTrigger' and have them change the tab page
    $(".TabTrigger").click(
        function (e) {
            $("#" + $(this).attr("class").split(" ")[1]).tabs("select", parseInt($(this).attr("class").split(" ")[2]));
            return false;
        }
    );

    // If there is a variable called initialTab, use it to make a tab visible 
    // Format is "selector tabNumber", e.g. "#TabStrip 2"
    if (typeof (initialTab) != "undefined") {
        $(initialTab.split(" ")[0]).tabs("select", parseInt(initialTab.split(" ")[1]));
    }

    // Progressive
    if ($(".Homepage").length == 0) {
        // Non-homepage progressive enhancement tweaks
        if ($.browser.msie && parseInt($.browser.version) == 6) {
            $("#Content").css("height", $("#MainContent").height() + "px");
            $("#NavigationWrap").css("height", $("#MainContent").height() + "px").wrapInner("<div id=\"NavigationWrapInner\"></div>");
            $("#FiltersWrap").wrap("<div id=\"FiltersWrapOuter\"></div>");
            $("#FiltersWrapOuter").css("height", $("#FiltersWrap").height() + "px");
        } else {
            $("#Content").css("min-height", $("#MainContent").height() + "px");
            $("#NavigationWrap").css("min-height", $("#MainContent").height() + "px").wrapInner("<div id=\"NavigationWrapInner\"></div>");
            $("#FiltersWrap").wrap("<div id=\"FiltersWrapOuter\"></div>");
            $("#FiltersWrapOuter").css("min-height", $("#FiltersWrap").height() + "px");
        }
    } else {
        // Homepage search filters
        $("select.SearchFilter").change(function () {
            $(this).parents(".VehicleSearch").find("div.SearchFilter, div.SearchFilterNone").hide()
            $("#" + $(this).val()).show();
        }).change();

        $(".FilterIcons img").click(function () {
            $(this).parents(".VehicleSearch").find("select.SearchFilter").val(findClass($(this), "Filters-")).change();
        });
    }

    // Modal Windows - don't just .jqm() it - there's a bug with that particular method
    if ($(".ModalTrigger").length > 0 || $(".ModalContent").length > 0) {

        $(".ModalContent").jqm({
            overlay: 66,
            modal: true,
            closeClass: "CloseModal"
        });
        $(".ModalTrigger").each(function () {

            if (this.tagName == "BUTTON" || this.tagName == "button") {
                // Use the button value as the target dialog
                $(this).click(function () {
                    if ($(this.attributes["value"].value).length > 0) {
                        $(this.attributes["value"].value).jqmShow();
                        return false;
                    }
                });
            }
            if (this.tagName == "A" || this.tagName == "a") {
                // Use the link's url as the target dialog
                $(this).click(function () {
                    if ($("#" + this.href.split("#")[1]).length > 0) {
                        $("#" + this.href.split("#")[1]).jqmShow();
                        return false;
                    }
                })
            }

            if (this.tagName == "INPUT" || this.tagName == "input") {
                // Use the input's class "Dialog-<dialogId>" to get the target dialog
                $(this).click(function () {
                    var CssClasses = $(this).attr("class").split(" ");

                    for (index in CssClasses) {
                        DialogClass = CssClasses[index];

                        if (DialogClass.indexOf("Dialog-") == 0) {
                            var dialogId = DialogClass.split("-")[1];
                            $("#" + dialogId).jqmShow();
                            return false;
                        }
                    }
                })
            }
        });

        if (openModal) {
            showModal($(openModal));
        }

    }

    $(".InitialisationRequired").removeClass("InitialisationRequired");

    $("input.CompareBox").click(function () {
        $("input.CompareBox:not(:checked)").attr("disabled", ($("input.CompareBox:checked").length >= 4));
    });
});

// 	The following functions are required by the routines above
function showModal(target) {
	if ($(target).length > 0) {
		$(target).jqmShow();
	}
}

function findClass(sourceObject, ClassPrefix) {
    var CssClasses = $(sourceObject).attr("class").split(" ");

    for (index in CssClasses) {
        CssClass = CssClasses[index];

        if (CssClass.indexOf(ClassPrefix) == 0) {
            return CssClass.replace(ClassPrefix, "");
            break;
        }
    }

    return undefined;
}

function digitGroup(num) {
	num += '';
	arrNum = num.split('.');
	intNum = arrNum[0];
	decNum = arrNum.length > 1 ? '.' + arrNum[1] : '';
	var regexGroup = /(\d+)(\d{3})/;
	while (regexGroup.test(intNum)) {
		intNum = intNum.replace(regexGroup, '$1' + ',' + '$2');
	}
	return intNum + decNum;
}

