String.prototype.endsWith = function(suffix) {
    return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
    return (this.substr(0, prefix.length) === prefix);
}

//Custom Plugins
$.easing.easeOutQuint = function(x, t, b, c, d) {
    return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
};

$.fn.clrTxt = function() {
    return this.focus(function() {
        if (this.value == this.defaultValue) {
            this.value = "";
        }
    }).blur(function() {
        if (!this.value.length) {
            this.value = this.defaultValue;
        }
    });
};

$.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({ opacity: 'toggle' }, speed, easing, callback);
};

$.fn.showMsg = function(message, type, onStart, onComplete) {
    var content = "<div style='border:solid 1px #ccc; padding:3px; font-size:1.5em; min-height:50px; min-width: 300px;'>" + message + "</div>"
    this.fancybox({
        enableEscapeButton: false,
        showCloseButton: type,
        hideOnOverlayClick: type,
        content: content,
        overlayOpacity: 0.7,
        overlayColor: '#000',
        onStart: function() {
            if (onStart) {
                onStart();
            }
        },
        onComplete: function() {
            $.fancybox.resize();
            if (onComplete) {
                onComplete();
            }
        }
    });
};

$(document).ready(function() {
    Init();
    var dealerID, domain, paymentUrl;

    function Init() {
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/Service/AjaxService.asmx/GetConfigInfo",
            dataType: "json",
            error: function(ex) {
                alert(ex.responseText);
            },
            success: function(data) {
                if (data != null) {
                    var split = data.d.split('|');
                    domain = split[0];
                    dealerID = split[1];
                }
            }
        });
    }

    $('.homeInfiniteCarousel').infiniteCarousel(0);

    /*Theme change*/
    $('a.scriptThemeChange').click(function() {
        var themeName = $(this).attr("id");

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "/Service/AjaxService.asmx/ThemeChange",
            data: "{themeName:'" + themeName + "'}",
            dataType: "json",
            error: function(ex) {
                alert(ex.responseText);
            },
            success: function(data) {
                $("#theme").attr("href", "/App_Themes/" + themeName + "/themes.css");
            }
        });
    });

    /*Promo Tile Matching*/
    var promoMaxHeight = 0;

    $('.promoArea > div').each(function() {
        if (!$(this).hasClass("shiftup")) {
            if ($(this).height() > promoMaxHeight) { promoMaxHeight = $(this).height(); }
        }
    });
    $('.promoArea > div').height(promoMaxHeight + 5).addClass('hasScript');


    /* Sort Comparison Tables */
    $('#cAccordion div table').each(function() {
        $('tr:last', this).addClass("last");
    });

    //site search
    $('.header .siteSearch').keypress(function(e) {
        if (e.which == 13) {
            $('.header .siteSearchbtn').click();
            return false;
        }
    });

    $('.header .siteSearchbtn').click(function() {
        var searchContent = $('.siteSearch').val();
        var link;
        if (searchContent.length > 0 && searchContent != 'Search') {
            if (domain == "") {
                link = "http://www.google.com/search?num=10&as_q=" + searchContent;
            }
            else {
                link = "http://www.google.com/search?as_sitesearch=" + domain + "&num=10&as_q=" + searchContent;
            }
            window.open(link);
        }
    })

    // dealer search
    $('#content .findaDealer .dealerSearch').keypress(function(e) {
        if (e.which == 13) {
            $('#content .findaDealer .dealerSearchbtn').click();
            return false;
        }
    });

    //dealer click
    $('#content .findaDealer .dealerSearchbtn').click(function() {
        var code = $('#content .findaDealer .dealerSearch').val();
        if (code.length > 0 && code != 'Enter your Postcode') {
            var url = 'http://dl.hondampe.com.au/NearestDealerships.aspx?SearchType=Location&Search=' + code + '&Assortment=';
            if (dealerID != '') {
                url += '&d=' + dealerID;
            }

            window.open(url);
        }
    });

    /* Tabs */
    var tabContainers = $('div.tabContainer > div');
    tabContainers.hide().filter(':first').show();
    $('div.tabs ul a').click(function() {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.tabs ul a').removeClass('active');
        $(this).addClass('active');
        Cufon.replace('.tabs a');
        return false;
    }).filter(':first').click();

    /* Media Selector */
    var mediaContainer = $('#mediaContainer > div');
    var mediaId;

    /* Color Event */
    // color thumbnail click event
    $('#rightTool .product-color li #colorthumbnail').live('click', function() {
        mediaContainer.hide();
        mediaContainer.filter(this.hash).show();
        var _self = this;

        $('#rightTool .product-color li a').each(function() {
            $(this).removeClass('active');
            if (this.id == 'colorthumbnail') {
                $(this).css('display', 'block');
            } else {
                $(this).css('display', 'none');
            };
        });
        $(_self).addClass('active');

        var $fancyItem = $(this.parentNode).find('#colorfancybox');
        var href = $fancyItem.attr('href');
        if (href != null && href != '') {
            $(_self).css('display', 'none');
            $fancyItem.css('display', 'block');
            $fancyItem.addClass('active')
        };

        return false;
    })
    // color fancy box mouse down event
    $('#rightTool .product-color li #colorfancybox').live('mousedown', function() {
        var $item = $(this);
        var fileSRC = $item.attr('test');

        $item.fancybox({
            titleShow: true,
            title: fileSRC,
            overlayOpacity: 0.7,
            overlayColor: '#000'
        });

        return false;
    });


    /* Media Event */
    mediaContainer.hide().filter(':first').show(function() {
        mediaId = this.id;

        var $thumbnailItem = $('.supportingMedia li').filter(':first').find('#thumbnail'),
             $fancyItem = $('.supportingMedia li').filter(':first').find('#fancyBox');
        var href = $fancyItem.attr('href');
        if (href != null && href != '') {
            $thumbnailItem.css('display', 'none');
            $fancyItem.css('display', 'block');
            $fancyItem.addClass('active')
        };
    });

    $('.supportingMedia li #thumbnail').live('click', function() {
        mediaContainer.hide();
        mediaContainer.filter(this.hash).show();
        var $item = $(this)
        $('.supportingMedia li a').removeClass('active');
        $item.addClass('active');

        $('.supportingMedia li a').each(function() {
            if (this.id == 'thumbnail') {
                $(this).css('display', 'block');
            } else {
                $(this).css('display', 'none');
            };
        });

        var $fancyItem = $(this.parentNode).find('#fancyBox');
        var href = $fancyItem.attr('href');
        if (href != null && href != '') {
            $item.css('display', 'none');
            $fancyItem.css('display', 'block');
            $fancyItem.addClass('active')
        };

        return false;
    });

    $('.supportingMedia li #fancyBox').live('mousedown', function() {
        var $item = $(this);
        var fileSRC = $item.attr('test');

        $item.fancybox({
            titleShow: true,
            title: fileSRC,
            overlayOpacity: 0.7,
            overlayColor: '#000'
        });

        return false;
    });

    /* Browse More Products */
    var initC = 0;
    var isopen = 0;
    var m_is_over = 0;
    $('.scriptShowProducts').click(function() {
        if (isopen == 0) {
            isopen = 1;
            $('#content .productDetail .overlayProducts').slideDown({ duration: 900, 'easing': "easeOutQuint" });
            $('.infiniteCarousel').infiniteCarousel(initC);
            initC = 1;
        } else {
            isopen = 0;
            $('#content .productDetail .overlayProducts').slideUp("fast")
        }
        return false;
    });


    function clearOverlay() {
        if (m_is_over == 0) {
            $('#content .productDetail .overlayProducts').slideUp("fast")
            isopen = 0;
        }
    }

    $('#content .productDetail .overlayProducts').mouseenter(function() {
        //clearTimeout work around
        m_is_over = 1;
    });

    $('#content .productDetail .overlayProducts').mouseleave(function() {
        m_is_over = 0;
        var pt = window.setTimeout(clearOverlay, 1000);
    });

    /* Accordion */
    $('#cAccordion h5').addClass('ui-accordion-header');
    $('#cAccordion h5').hover(function() {
        $(this).addClass('ui-state-hover');
    }, function() {
        $(this).removeClass('ui-state-hover');
    });
    $('#cAccordion h5').click(function() {
        $(this).next().slideToggle('slow');
        $(this).toggleClass('ui-state-active');
        return false;
    }).next().hide();
    $('#cAccordion h5').first().trigger('click');

    /* Input Text Fields Clear Defaults */
    $('input.siteSearch').clrTxt();
    $('input.dealerSearch').clrTxt();

    /* Fancy MultiMedia */
    $("a.scriptFancyMedia").live("mousedown", function() {
        $item = $(this);
        var contentid = $item.attr("id");
        var hits = $item.parent().find("#hits");

        $item.fancybox({
            titleShow: true,
            overlayOpacity: 0.7,
            overlayColor: '#000',
            onComplete: function() {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "/Service/AjaxService.asmx/ImageCounter",
                    data: "{contentID:'" + contentid + "'}",
                    dataType: "json",
                    error: function(ex) {
                        alert(ex.responseText);
                    },
                    success: function(data, status) {
                        if (data.d) {
                            hits.text(Number(hits.text()) + 1);
                        }
                    }
                });
            }
        });
    });

    $(".standardDetail a.FancyMedia").live("mousedown", function() {
        $item = $(this);

        $item.fancybox({
            titleShow: true,
            overlayOpacity: 0.7,
            overlayColor: '#000'
        });
    });

    $('#mediaContainer .supportingTools a').mousedown(function(e) {
        $item = $(this);
        var fileSRC = $item.attr('test');
        var url = "<a href=/Download.aspx?FileSRC=" + escape(fileSRC) + "&timestamp=" + new Date().getTime() + " class=largeDownload>Download</a>";

        $item.fancybox({
            titleShow: true,
            title: url,
            overlayOpacity: 0.7,
            overlayColor: '#000'
        });
    });

    $('#mediaContainer .supportingTools').each(function() {
        $fancyItem = $(this).find('a');
        var href = $fancyItem.attr('href');
        if (href == null || href == "") {
            $fancyItem.hide();
        }
    });

    /* Tools */
    $('a.tlPrint').show();
    $('a.tlPrint').click(function() { window.print(); return false; });
    $('a.tlShare').show();

    /* x-ray */
    $('a.xray').click(function() {
        $(this).parent().parent().find('img').fadeToggle();
        return false;
    });

    /*Download*/
    $('#contentArea .galleryListing .download').live("click", function() {
        var $item = $(this);
        $item.attr('href', '');
        var href = '/Download.aspx?FileSRC=' + escape($item.attr('url')) + '&timestamp=' + new Date().getTime();
        $item.attr('href', href);
    });

    /*Invoice*/
    // Check input
    var $quantityBox = $("input[type='text'].quantityField");
    $quantityBox.live("keypress", function(e) {
        if (((e.which <= 57 && e.which >= 48) || (e.which == 8)) && (e.which != 102)) {
            return true;
        }
        return false;
    });

    $quantityBox.each(function() {
        var val;
        $(this).bind("keydown", function() {
            this.val = $(this).val();
        }).bind("keyup", function() {
            if (!/^[\d]*$/.test($(this).val())) {
                $(this).val(this.val);
            }
        });
    });

    Cufon.now();

});
//End Document Ready

/* Cufon Titles */
Cufon.replace('h1,h2,h3,h4,.title,.tileButton,.formlabel,.totalHeading,.tabs a, .buyOnBtn,.buyOffBtn');

/* Share Link Config */
var addthis_config = {
    ui_offset_top: -4,
    ui_offset_left: -192
}

