/// <reference path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.3.2-vsdoc.js" />
/// <reference path="facebox.js" />

$(document).ready(function () {
    if ($.browser.msie && $.browser.version == "6.0") {
        DD_belatedPNG.fix('img, a, h2, span');
    };
    $('a.ext').click(function () {
        window.open($(this).attr('href'));
        return false;
    });
    $(".unsubscribePanel").hide();
    $(".subSelect input").click(function (e) {
        $(".subscribePanel").show();
        $(".unsubscribePanel").hide();
    });
    $(".unSelect input").click(function (e) {
        $(".subscribePanel").hide();
        $(".unsubscribePanel").show();
    });
    $('.subCats h2').ellipsis();
    $('#slider').nivoSlider({
        effect: 'slideInRight',
        pauseTime: 6000
    });

    //in field labels
    $(".over label").inFieldLabels();

    $('a.testfb').facebox();

    //Shows the videos in the categories
    $('.playVideo a.ir').click(function () {
        $('.video').slideDown();
        $('.content,.playVideo').hide();
        return false;
    });

    $('.countryToggle').click(function () {

        $('.countrySelector').toggleClass('drop');
        $('.countrySelector ul').slideToggle();

        return false;
    });

    $('.video .close').click(function () {
        $('.video').slideUp();
        $('.content,.playVideo').show();
        return false;
    });

    jQuery("abbr.timeago").timeago();
    var $bubble = $("#bubble");
    var $bubbleTitle = $("#bubble-title");
    var $bubbleText = $("#bubble-text");
    var bubbleTimer;
    $(".selections .extended .term").hover(function (event) {
        clearTimeout(bubbleTimer);
        bubbleTimer = setTimeout(function () {
            $bubbleText.text("^Pricing and offer based on an indefinite period rental agreement with a calculation period of 24 months. Full terms and conditions available on application.");
            var offset = $(event.target).offset();
            var width = $(event.target).width() / 2;
            $bubble.css({
                top: offset.top + 20,
                left: offset.left + width - 110
            })
            $bubble.show();
        }, 600);
    }, function () {
        clearTimeout(bubbleTimer);
        $bubble.hide();
    });
    $(".selections .long .term").hover(function (event) {
        clearTimeout(bubbleTimer);
        bubbleTimer = setTimeout(function () {
            $bubbleText.text("^^Pricing and offer based on an indefinite period rental agreement with a calculation period of 12 months. Full terms and conditions available on application.");
            var offset = $(event.target).offset();
            var width = $(event.target).width() / 2;
            $bubble.css({
                top: offset.top + 20,
                left: offset.left + width - 110
            })
            $bubble.show();
        }, 600);
    }, function () {
        clearTimeout(bubbleTimer);
        $bubble.hide();
    });
    $.setupSublist("country");
    $.setupSublist3("regions");
    $("li:first-child").addClass("first-child");
    $("li:last-child").addClass("last-child");
    $(".product-detail:last-child").addClass("last-child");
    $(".product-category .row:last-child").addClass("last-child");
    $("#body.container .more-rental .inner .item:last-child").addClass("last-child");
    $("#body.container .news-listing:last-child").addClass("last-child");
    $("#body.container .position-vacant .details:last-child").addClass("last-child");
    $('input[class="textbox"]').focus(function () {
        $(this).addClass("focus");
    });
    $('input[class="textbox"]').blur(function () {
        $(this).removeClass("focus");
    });
    $('#page-tools .font-increase').click(function () {
        $("body").css("font-size", "90%");
        return false;
    });
    $('#page-tools .font-decrease').click(function () {
        $("body").css("font-size", "80%");
        return false;
    });
    $(".print a").click(function () {
        var popurl;
        if (location.href.indexOf("?") != -1) {
            popurl = location.href + "&print=true";
        } else {
            popurl = location.href + "?print=true";
        }
        window.open(popurl, "Print", "toolbar=1,scrollbars=1,menubar=1,width=750,height=520");
        return false;
    });
    if (location.href.indexOf("print=true") != -1) {
        $("link").each(function () {
            if ($(this).attr("media") == "print") {
                if ($.browser.msie) {
                    $(this).attr("media", "all");
                } else {
                    $(this).replaceWith('<link rel="stylesheet" type="text/css" href="/includes/styles/print.css">');
                }
            } else {
                $(this).remove();
            }
        });
        $("a").attr("href", "#");
        $("body").append('<script type="text/javascript">print();</script>');
    }
    $(".faq-container").hide();
    $("h4.faq-title").toggle(function () {
        $(this).addClass("active");
    }, function () {
        $(this).removeClass("active");
    });
    $("h4.faq-title").click(function () {
        $(this).next(".faq-container").slideToggle("slow");
    });
    $(".glossary h2").hide();
    $('.glossary dl').hide();
    $('.glossary').prepend('<div class="navigation"><ul></ul></div>');
    var numLetters = $('.glossary h2').length;
    $('.glossary h2').each(function (i) {
        var title = $(this).text();
        var link;
        if ($('.glossary #' + title).length > 0) {
            link = '<li><a href="#' + title + '">' + title + '<span class="bottom"></span></a></li>';
        } else {
            link = '<li><span class="noitems">' + title + '</span></li>';
        }
        $('.glossary .navigation ul').append(link);
    });
    $('.glossary .navigation a').click(function () {
        $('.glossary .navigation ul li').removeClass("selected");
        $(this).parent("li").addClass("selected");
        var id = '#' + this.href.split('#')[1];
        $('.glossary dl').hide();
        $(id).show();
        return false;
    });
    $(".glossary dl:first").show();
    $(".glossary .navigation li:first").addClass("selected");
    $(".query").focus(function (srcc) {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    $(".query").blur(function () {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    $(".query").blur();
});
jQuery.setupSublist = function (keyword) {
    var $parent = $("select[rel=" + keyword + "-parent]");
    var $child = $("select[rel=" + keyword + "-child]");
    var $parentContainer = $parent.parent();
    var $childContainer = $child.parent();
    var $linkedFields = $("input[rel|=" + keyword + "]");
    var activeSelection = $parent.find("option:selected").attr("value");
    $linkedFields.parent().hide();
    var $childClone = $child.clone().appendTo($childContainer);
    $childClone.removeAttr("name").removeAttr("id").removeAttr("rel");
    $childClone.hide();
    updateChildOptions(activeSelection);
    updateLinkedFields(activeSelection);
    $parent.change(function () {
        var filter = $(this).find("option:selected").attr("value");
        if (filter != activeSelection) {
            updateChildOptions(filter);
            updateLinkedFields(filter);
        }
    });

    function updateChildOptions(filter) {
        $child.empty();
        $child.attr("disabled", "disabled");
        $child.append('<option value="null" selected="selected">-- Please select --</option>');
        $childClone.find("optgroup[label='" + filter + "'] option").each(function (index) {
            if (index == 0) {
                $child.removeAttr("disabled");
            }
            $child.append($(this).clone());
            activeSelection = filter;
        });
    }

    function updateLinkedFields(filter) {
        $linkedFields.parent().hide();
        $linkedFields.each(function () {
            var simpleFilter = filter.split(' ').join('').toLowerCase();
            if ($(this).attr("rel") == keyword + "-" + simpleFilter) {
                $(this).parent().show();
            }
        });
    }
};
jQuery.setupSublist3 = function (keyword) {
    var $parent = $("select[rel=" + keyword + "-parent]");
    var $child = $("select[rel=" + keyword + "-child]");
    var $sibling = $("select[rel=" + keyword + "-sibling]");
    var $parentContainer = $parent.parent();
    var $childContainer = $child.parent();
    var $siblingContainer = $sibling.parent();
    var activeSelection = $parent.find("option:selected").attr("value");
    var activeChildSelection = $child.find("option:selected").attr("value");
    var $childClone = $child.clone().appendTo($childContainer);
    $childClone.removeAttr("name").removeAttr("id").removeAttr("rel");
    $childClone.hide();
    var $siblingClone = $sibling.clone().appendTo($siblingContainer);
    $siblingClone.removeAttr("name").removeAttr("id").removeAttr("rel");
    $siblingClone.hide();
    updateChildOptions(activeSelection);
    updateSiblingOptions(activeChildSelection);
    $parent.change(function () {
        var filter = $(this).find("option:selected").attr("value");
        if (filter != activeSelection) {
            updateChildOptions(filter);
        }
        if (filter != activeChildSelection) {
            updateSiblingOptions(filter);
        }
    });
    $child.change(function () {
        var filter = $(this).find("option:selected").attr("value");
        if (filter != activeChildSelection) {
            updateSiblingOptions(filter);
        }
    });

    function updateChildOptions(filter) {
        $child.empty();
        $child.attr("disabled", "disabled");
        $child.append('<option value="null" selected="selected">-- Please select your state/island --</option>');
        $childClone.find("optgroup[label='" + filter + "'] option").each(function (index) {
            if (index == 0) {
                $child.removeAttr("disabled");
            }
            $child.append($(this).clone());
            activeSelection = filter;
        });
    }

    function updateSiblingOptions(filter) {
        $sibling.empty();
        $sibling.attr("disabled", "disabled");
        $sibling.append('<option value="null" selected="selected">-- Please select your region --</option>');
        $siblingClone.find("optgroup[label='" + filter + "'] option").each(function (index) {
            if (index == 0) {
                $sibling.removeAttr("disabled");
            }
            $sibling.append($(this).clone());
            activeChildSelection = filter;
        });
    }
};
Cufon.replace('.form h2');
Cufon.replace('.form h2');
Cufon.replace('.product-info h2');

/* ads attribute */
$.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};


var mrRental = {
    postCodeSearch: {
        control: null,
        init: function (selector) {
            //select the control, either textbox or select box
            control = $('#' + selector + ' input[type=text], #' + selector + ' select');

            //set up the facebox show
            $(document).bind("reveal.facebox", function () {
                var submit = $("#facebox input[type=submit]");

                //fix up the ids to be unique for the field labels
                $("#facebox input, #facebox label").each(function () {
                    var item = $(this);
                    item.attr("id", item.attr("id") + "_facebox");
                    if (item.hasAttr("for"))
                          item.attr("for", item.attr("for") + "_facebox");
                });

                $("#facebox input[type=text]").removeAttr("name").keyup(function () {
                    control.val(this.value);
                }).keypress(function (e) {
                    if (e.keyCode == '13') {
                        e.preventDefault();
                        submit.click();
                    }
                });

                $("#facebox select").removeAttr("name").change(function () {
                    control.val($(this).val());
                });

                //add tracking
                submit.click(mrRental.postCodeSearch.trackingClick);
            });

            //show the facebox
            jQuery.facebox({ div: '#' + selector });

            //add tracking
            $("#" + selector + " input[type=submit]").click(mrRental.postCodeSearch.trackingClick);

        },
        trackingClick: function () {
            try {
                var data = control.val();

                //for the drop down we need to use the text
                if (control.is("select"))
                    data = jQuery.trim(control.find("option:selected").text());

                mrRental.log(data);
                _gaq.push(['_trackEvent', 'Store Lookup', 'Submit', data]);
            } catch (err) {
                mrRental.log(err, true);
            }
        }
    },
    log: function (message, error) {
        if (typeof (console) != "undefined")
            if (error)
                console.error(message);
            else
                console.log(message);
    }
};

