﻿jQuery.fn.jTube = function () {

    return this.each(function() {
        // get jQuery version of 'this'
        var $input = jQuery(this),
            url = $input.attr('href');

        if (url == undefined) {
            return null;
        }

        var img;
        var vid;
        var results;

        results = url.match("[\\?&]v=([^&#]*)");

        vid = (results === null) ? url : results[1];
        img = "http://img.youtube.com/vi/" + vid + "/2.jpg";
        //$input.html('<img src="http://img.youtube.com/vi/'+vid+'/2.jpg" alt="" />');
        //$input.css('background-image', 'url("' + img + '")');
        $('#movie img').attr('src', img);
    });
};

jQuery.fn.hint = function (blurClass) {
    if (!blurClass) {
        blurClass = 'blur';
    }

    return this.each(function () {
        // get jQuery version of 'this'
        var $input = jQuery(this),

        // capture the rest of the variable to allow for reuse
	  title = $input.attr('title'),
	  $form = jQuery(this.form),
	  $win = jQuery(window);

        function remove() {
            if ($input.val() === title && $input.hasClass(blurClass)) {
                $input.val('').removeClass(blurClass);
            }
        }

        // only apply logic if the element has the attribute
        if (title) {
            // on blur, set value to title attr if text is blank
            $input.blur(function () {
                if (this.value === '') {
                    $input.val(title).addClass(blurClass);
                }
            }).focus(remove).blur(); // now change all inputs to title

            // clear the pre-defined text when form is submitted
            $form.submit(remove);
            $win.unload(remove); // handles Firefox's autocomplete
        }
    });
};

$(document).ready(function () {

    var theWindow = $(window),
            $bg = $("#bg"),
            aspectRatio = $bg.width() / $bg.height();

    //if(theWindow.width() >= 950){}
    RandomBackground(theWindow);


    function resizeBg() {

        if ((theWindow.width() / theWindow.height()) < aspectRatio) {
            $bg
                        .removeClass()
                        .addClass('bgheight');
        } else {
            $bg
                        .removeClass()
                        .addClass('bgwidth');
        }

    }

    theWindow.resize(function () {
        resizeBg();
    }).trigger("resize");



    $('#spotLightSlider').anythingSlider({
        easing: "swing",    // Anything other than "linear" or "swing" requires the easing plugin
        autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 7500,                    // How long between slide transitions in AutoPlay mode
        animationTime: 1200,             // How long the slide transition takes
        buildNavigation: false,          // If true, builds and list of anchor links to link to each slide
        pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
        navigationFormatter: null,       // Details at the top of the file on this use (advanced use)
        buildStartStop: false,
        buildArrows: false
    });

    $("a[rel^='prettyPhoto']").prettyPhoto({
        social_tools: false
    });

    $('#movie a').jTube();
    $("input").hint();
    $("textarea").hint();

    $('a#BuyThisProduct').bind('click', function () {
        $('#buyForm').show();
        $('#infoForm').hide();
        $('#visibleInfoForm').hide();
        $('#mailProduct').hide();
        $('#VisiblemailProduct').hide();
        //$('#productDescription input#Name').focus();
        var newPosition = $('#productDescription').offset();
        window.scrollTo(newPosition.left, newPosition.top);
        return false;
    });

    $('a#MoreInformation').bind('click', function () {
        $('#infoForm').show();
        $('#buyForm').hide();
        $('#visibleBuyForm').hide();
        $('#mailProduct').hide();
        $('#VisiblemailProduct').hide();
        //$('#productDescription textarea#Remarks').focus();
        var newPosition = $('#productDescription').offset();
        window.scrollTo(newPosition.left, newPosition.top);
        return false;
    });

    $('a#MailProduct').bind('click', function () {
        $('#mailProduct').show();
        $('#infoForm').hide();
        $('#visibleinfoForm').hide();
        $('#buyForm').hide();
        $('#visibleBuyForm').hide();
        $('#productDescription input#Name').focus();
        return false;
    });



    $('input#Name').bind('blur', function () {
        $('p#customerName').html($(this).attr('value'));
    });
    $('input#EmailAddress').bind('blur', function () {
        $('p#customerEmail').html($(this).attr('value'));
    });
    $('input#PhoneNumber').bind('blur', function () {
        $('p#customerPhone').html($(this).attr('value'));
    });

    $('#pageNavigation').hide();

    $('#productPageOptions ul').prepend('<li class="printPage"><a href="#print">print</a></li>');
    $('#productPageOptions ul li.printPage').live('click', function () {
        window.print();
        return false;
    });

    /*$('#smallImages img').bind('click', function () {
    var src = $(this).attr('src');
    var fileName = src.split('/').pop();
    var currentFileName = $('#largeImage a').attr('href').split('/').pop();
    src = src.replace('/84/85/', '/440/340/');
    $('#largeImage img').attr('src', src);
    $('#largeImage a').attr('href', $('#largeImage a').attr('href').replace(currentFileName, fileName));
    return false;
    });*/

    $('li.wishList').bind('click', function () {
        var url = $(this).children('a').attr('href');
        AddToWishList(url);
        return false;
    });

    $('a.removeInspiration').bind('click', function () {
        var url = $(this).attr('href');
        RemoveFromWishList(url);
        $(this).parent().parent().parent().remove();
        var products = $('#wishListTable').children().children().size();
        //console.debug(products);
        if (products == 0) {
            $('p.clearList').remove();
        }
        return false;
    });

    $('a.removeAllInspiration').bind('click', function () {
        var url = $(this.attr('href'));
        RemoveWishList(url);
        $(this).parent().parent().parent().remove();
        $('p.clearList').remove();
        return false;
    });




    // Make sure to only match links with a rel tag, .footerSubItem parent and toolTip class
    $('.footerSubItem a[rel].toolTip').each(function () {
        // We make use of the .each() loop to gain access to each element via the "this" keyword...
        $(this).qtip(
            {
                content: {
                    // Set the text to an image HTML string with the correct src URL to the loading image you want to use
                    text: '<img class="throbber" src="/Content/Images/throbber.gif" alt="Loading..." />',
                    ajax: {
                        url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
                    },
                    title: {
                        text: '', // Give the tooltip a title using each elements text
                        button: false
                    }
                },
                position: {
                    my: 'left center',
                    at: 'right center', // Position the tooltip next to list item
                    target: $(this).parent(),
                    viewport: $(window), // Keep the tooltip on-screen at all times
                    effect: false // Disable positioning animation
                },
                show: {
                    event: 'mouseenter',
                    solo: true // Only show one tooltip at a time
                },
                hide: 'mouseleave',
                style: {
                    classes: 'ui-tooltip-wiki ui-tooltip-light ui-tooltip-shadow'
                }
            });
    });

    // Make sure to only match links with a rel tag, .product parent and toolTip class
    $('.product a[rel].toolTip').live('mouseover', function () {
        // We make use of the .each() loop to gain access to each element via the "this" keyword...
        $(this).qtip(
            {
                content: {
                    // Set the text to an image HTML string with the correct src URL to the loading image you want to use
                    text: '<img class="throbber" src="/Content/Images/throbber.gif" alt="Loading..." />',
                    ajax: {
                        url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
                    },
                    title: {
                        text: '', // Give the tooltip a title using each elements text
                        button: false
                    }
                },
                position: {
                    my: 'center',
                    at: 'center', // Position the tooltip next to list item
                    target: $(this).parent(),
                    viewport: $(window), // Keep the tooltip on-screen at all times
                    effect: false // Disable positioning animation
                },
                show: {
                    //event: 'mouseenter',
                    ready: true,
                    solo: true // Only show one tooltip at a time
                },
                hide: 'unfocus',
                style: {
                    classes: 'ui-tooltip-wiki ui-tooltip-light ui-tooltip-shadow'
                }
            });
    });



});

$(window).load(function () {
    $('img#bg').fadeIn();
});

$(window).scroll(function () {
    if ($('#objectScroll').html() != null) {
        if (($(window).scrollTop() + 300) > ($(document).height() - $(window).height())) {
            loadMoreProducts();
        }
    }
    if ($('#newsList').html() != null) {
        if (($(window).scrollTop() + 300) > ($(document).height() - $(window).height())) {
            loadMoreNewsItems();
        }
    }
});

var xhr = null;
    
function loadMoreProducts() {
    var nextPage = $("#pageNavigation a[class~='pageLink']").not('.linkLoaded');
    if(nextPage.length > 0) {   
        if (xhr == null) {
            $(nextPage[0]).addClass("linkLoaded");

            xhr = $.ajax({
                    url: $(nextPage[0]).attr("href"),
                    success: function(data) {
                        $(".horizontalObjectList").append(data);
                        xhr = null;
                    }
                });
        }
    }
}


function loadMoreNewsItems() {
    var nextPage = $("#pageNavigation a[class~='pageLink']").not('.linkLoaded');
    if (nextPage.length > 0) {
        if (xhr == null) {
            $(nextPage[0]).addClass("linkLoaded");

            xhr = $.ajax({
                url: $(nextPage[0]).attr("href"),
                success: function (data) {
                    $("#newsList").append(data);
                    xhr = null;
                }
            });
        }
    }
}


function RandomBackground(window) {
    var maxImage = 11;
    var randomNumber = Math.round(Math.random() * (maxImage - 1)) + 1;
    var windowWidth = window.width();
    var imageWidth = 1024;

    if (windowWidth <= 1024) {
        imageWidth = 1024;
    }
    else if (windowWidth <= 1280) {
        imageWidth = 1280;
    }
    else if(windowWidth <= 1366) {
        imageWidth = 1366;
    }
    else if(windowWidth <= 1440) {
        imageWidth = 1440;
    }
    else if(windowWidth <= 1680) {
        imageWidth = 1680;
    }
    else if(windowWidth > 1680) {
        imageWidth = 1920;
    }


    var imgPath = '/site/images/cache/' + imageWidth + '/0/' + randomNumber + '.jpg';
    $('img#bg').attr('src', imgPath);
}

function AddToWishList(url) {
    $.getJSON(url, function (json) {
        if (json.Success) {
            $('.wishList').html(json.Message);
        }
    });
}

function RemoveFromWishList(url) {
    $.getJSON(url, function (json) {
        return json.Success;
    });
}

function RemoveWishList(url) {
    $.getJSON(url, function (json) {
        return json.Success;
    });
}

