﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/* Dimension details loader 

*/
;(function($) {
    $.dimLoader = function(options) {
        var o = $.extend({
            itemId: 0,
            imgWidth: 120,
            imgMod: 'crop=none',
            drp1: '',
            drp2: '',
            drp3: '',
            prodNo: '',
            stock: '',
            price: '',
            orig: '',
            disc: '',
            image: '',
            error: '',
            buyRow: '',
            priceFrom: '',
            loadImg: R + 'Startup/Pics/wait3.gif'
        }, options || {});
        
        var loadImg = '<img alt="loading..." src="' + o.loadImg + '" />';
        var d1 = $(o.drp1),
        d2 = $(o.drp2),
        d3 = $(o.drp3),
        drp = d1.add(d2).add(d3),
        prodNo = $(o.prodNo),
        stock = $(o.stock),
        price = $(o.price),
        orig = $(o.orig),
        disc = $(o.disc),
        image = $(o.image),
        error = $(o.error),
        buyRow = $(o.buyRow);

        if (drp.length > 0) {
            //Hookup change event
            drp.change(function() {
                //Set loading image
                prodNo.add(stock).add(price).add(orig).add(disc).html(loadImg);

                //Check if all dims are selected
                var allSel = drp.filter(function() { return jQuery("option:selected", this).val() !== "0"; }).length === drp.length;

                //Fetch dim details
                $.publicFetch({
                    handler: "ProductData",
                    data: {
                        a: "GetDimDetails",
                        ItemID: o.itemId,
                        Dim1: d1.length > 0 ? d1.find("option:selected").val() : "0",
                        Dim2: d2.length > 0 ? d2.find("option:selected").val() : "0",
                        Dim3: d3.length > 0 ? d3.find("option:selected").val() : "0",
                        ImageWidth: o.imgWidth,
                        ImgMod: o.imgMod
                    },
                    success: function(d) {
                        //Allow buy
                        buyRow.css("display", d.AllowBuy === true || allSel === false ? "" : "none");
                        //Product number
                        prodNo.text(d.ProdNo);
                        //Stock text
                        stock.text(d.StockText);
                        stock.css("color", d.StockColor);
                        //Price
                        price.text((allSel === false ? o.priceFrom : "") + d.Price);
                        //Original price
                        orig.text(d.OriginalPrice);
                        //Discount price
                        disc.text(d.Discount);
                        //Image
                        if (d.ImageURL.length > 0) {
                            //Set image url
                            image.attr("src", d.ImageURL);
                        }
                    },
                    error: function(err) {
                        if (error.hasClass('ErrMsg')) { error.text(err.Message); }
                        else {
                            if (error.find('.ErrMsg').length > 0) { error.find('.ErrMsg').text(err.Message); }
                            else { error.append('<span class="ErrMsg">' + err.Message + '</span>'); }
                        }

                        prodNo.add(stock).add(price).add(orig).add(disc).html("");
                    }
                });
            });
        }
    };
})(jQuery);

/* Auto grow textbox
jQuery('input#myinput').autoGrowInput({
    comfortZone: 50,
    minWidth: 200,
    maxWidth: 2000
});
*/
(function(jQuery) {

    jQuery.fn.autoGrowInput = function(o) {

        o = jQuery.extend({
            maxWidth: 1000,
            minWidth: 0,
            comfortZone: 70
        }, o);

        this.filter('input:text').each(function() {

            var minWidth = o.minWidth || jQuery(this).width(),
                val = '',
                input = jQuery(this),
                testSubject = jQuery('<div/>').css({
                    position: 'absolute',
                    top: -9999,
                    left: -9999,
                    width: 'auto',
                    fontSize: input.css('fontSize'),
                    fontFamily: input.css('fontFamily'),
                    fontWeight: input.css('fontWeight'),
                    letterSpacing: input.css('letterSpacing'),
                    whiteSpace: 'nowrap'
                }),
                check = function() {

                    if (val === (val = input.val())) { return; }

                    // Enter new content into testSubject
                    var escaped = val.replace(/&/g, '&amp;').replace(/\s/g, '&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                    testSubject.html(escaped);

                    // Calculate new width + whether to change
                    var testerWidth = testSubject.width(),
                        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                        currentWidth = input.width(),
                        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                             || (newWidth > minWidth && newWidth < o.maxWidth);

                    // Animate width
                    if (isValidWidthChange) {
                        input.width(newWidth);
                    }

                };

            testSubject.insertAfter(input);

            jQuery(this).bind('keyup keydown blur update', check);

        });

        return this;

    };

})(jQuery);

/* function to wait
 * jQuery("stuff").wait(2000);
 */
(function(jQuery) {
    jQuery.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                jQuery(self).dequeue();
            }, time);
        });
    };
})(jQuery);

/* loadUC
* jQuery("div.UCinHERE").loadUC("/Handlers/EStore/TempOrderLines.ascx", true);
*/
(function(jQuery) {
    jQuery.fn.loadUC = function(path) {
        this.each(function() {
            jQuery(this).load(R + "Handlers/RenderUserControl.ashx?path=" + path);
        });

        return this;
    };
})(jQuery);

/**
* Create a cookie with the given key and value and other optional parameters.
*
* SET
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* GET
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*/
jQuery.cookie = function(key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function(s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

(function(jQuery) {
    jQuery.fn.extend({
        check: function() {
            return this.filter(":radio, :checkbox").attr("checked", true);
        },
        uncheck: function() {
            return this.filter(":radio, :checkbox").removeAttr("checked");
        }
    });
}(jQuery));

function SetupFancybox(items) {
    items.fancybox({
        transitionIn: "elastic",
        transitionOut: "elastic",
        speedIn: 300,
        speedOut: 300,
        changeSpeed: 300,
        changeFade: "fast",
        easingIn: "swing",
        easingOut: "swing",
        type: "image"
    });
}

// jQuery outerHTML
(function ($) {

    $.fn.extend({
        outerHTML: function (value) {

            // Replaces the content
            if (typeof value === "string") {
                var $this = $(this),
					$parent = $this.parent();

                var replaceElements = function () {

                    // For some reason sometimes images are not replaced properly so we get rid of them first
                    var $img = $this.find("img");
                    if ($img.length > 0) {
                        $img.remove();
                    }

                    var element;
                    $(value).map(function () {
                        element = $(this);
                        $this.replaceWith(element);
                    })

                    return element;

                }

                return replaceElements();

                // Returns the value
            } else {
                return $("<div />").append($(this).clone()).html();
            }

        }
    });

})(jQuery);

//Set equal heights
function SetEqualHeights() {
    //Define context (Controls)
    var context = jQuery(".UC101MainContainer, .UC132MainContainer, .UC130MainContainer, .UC134MainContainer, .UC120MainContainer, .UC111MainContainer, .UC137MainContainer, .UC124MainContainer");

    //Declare row containers
    var cont = context.find(".ListContainer > table > tbody > tr, .SubListContainer > table > tbody > tr");
    
    //Declare column containers, innermost containers first!
    var cols = new Array(".ItemTitleCont", ".ImageContainer", ".TeaserContainer", ".DescriptionContainer", ".ProdDetailsContainer", ".DocItemInnerContainer", ".ItemInnerContainer");
    
    //For each row container
    cont.each(function() {
        //For each columns container
        for (x = 0; x < cols.length; x++) {
            //Declare items, a new array for heights and an index counter
            items = jQuery(this).find(cols[x]), its = new Array(), cr = 0;

            //Check item count
            if (items.length > 1) {
                //Get all heights
                items.each(function() { its[cr] = jQuery.browser.chrome ? jQuery(this).height() : jQuery(this).innerHeight(); cr++; });

                //Set heights to max
                items.css('height', Math.max.apply(Math, its) + 'px');
            }
        }
    });
}

(function($) {
    $.publicFetch = function(options) {
        //Build options
        options = $.extend({
            handler: "",
            data: {},
            success: undefined,
            error: undefined
        }, options || {});

        //Shorthand
        var t = this;
        var o = options;

        //Append page and item id
        o.data.BasePageID = BasePageID;
        o.data.BaseItemID = BaseItemID;

        //Ajax
        if (o.handler.length > 0) {
            $.ajax({
                url: R + "Handlers/Public/" + o.handler + ".ashx",
                data: o.data,
                success: function(data) { if (o.success !== undefined) { o.success(data); } },
                error: function(err) {
                    //Parse error message
                    var msg = {};
                    try { msg = $.parseJSON(err.responseText); }
                    catch (ex) { msg = { Message: err.responseText }; }

                    //Log to console if available
                    if (console && console.log) { console.log(msg); }

                    //Call error callback
                    if (o.error !== undefined) {
                        o.error(msg);
                    }
                }
            });
        }
    };
})(jQuery);

//Document ready
if (typeof jQuery !== undefined) {
    
    //Define user agent
    var userAgent = navigator.userAgent.toLowerCase();

    // Figure out what browser is being used
    jQuery.browser = {
        version: (userAgent.match(/.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/) || [])[1],
        chrome: /chrome/.test(userAgent),
        safari: /webkit/.test(userAgent) && !/chrome/.test(userAgent),
        opera: /opera/.test(userAgent),
        msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
        mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
    };
    
    jQuery(document).ready(function() {
        //If tooltip is loaded, set tooltip
        if (jQuery.tooltip) {
            jQuery(".Tooltip").tooltip({
                delay: 0,
                showURL: false,
                showBody: " - "
            });
        }
        //If fancybox is loaded
        if (typeof jQuery.fancybox !== undefined) {
            //Remove title where title=" "
            jQuery("a[rel^='lightbox']").each(function() {
                var thisOne = jQuery(this);
                if (thisOne.attr("title") && ((thisOne.attr("title").length == 1 && thisOne.attr("title").charCodeAt(0) == 160) || thisOne.attr("title") == ""))
                    thisOne.removeAttr("title");
            });
            //Setup fancybox
            SetupFancybox(jQuery("a[rel^='lightbox']"));
        }
    });
}

//Window load
if (typeof jQuery != 'undefined') {
    jQuery(window).load(function() {
        //Set container heights for column controls
        SetEqualHeights();
    });
}
