

function Set_Cookie( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
function Delete_Cookie( name, path, domain )
{
    if ( Get_Cookie( name ) )
    {
        document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

jQuery.fn.pulse = function( prop, speed, times, easing, callback ) {
    
    if ( isNaN(times) ) {
        callback = easing;
        easing = times;
        times = 1;
    }
    
    var optall = jQuery.speed(speed, easing, callback),
        queue = optall.queue !== false,
        largest = 0;
    
    var p;
    for (p in prop)
    {
        largest = Math.max(prop[p].length, largest);
    }
    
    optall.times = optall.times || times;
    
    return this[queue?'queue':'each'](function(){
        var counts = {},
            opt = jQuery.extend({}, optall),
            self = jQuery(this);
        function pulse() {
            var propsSingle = {},
                doAnimate = false;
            for (var p in prop) {
                // Make sure counter is setup for current prop
                counts[p] = counts[p] || {runs:0,cur:-1};
                // Set "cur" to reflect new position in pulse array
                if ( counts[p].cur < prop[p].length - 1 ) {
                    ++counts[p].cur;
                } else {
                    // Reset to beginning of pulse array
                    counts[p].cur = 0;
                    ++counts[p].runs;
                }
                if ( prop[p].length === largest ) {
                    doAnimate = opt.times > counts[p].runs;
                }
                propsSingle[p] = prop[p][counts[p].cur];
            }
            opt.complete = pulse;
            opt.queue = false;
            if (doAnimate) {
                self.animate(propsSingle, opt);
            } else {
                optall.complete.call(self[0]);
            }
        }
        pulse();
            
    });
    
};
jQuery.defer = function(delay, callback)
{
    var timer;
     
    // Return the callback proxy
    return function()
    {
        // Save the vars for the real callback
        var that = this, args = arguments;
     
        // Reset the delay
        window.clearTimeout(timer);
         
        // Delay the real callback
        timer = window.setTimeout(function()
        {
            callback.apply(that, args);
        }, delay);
    };
};

$(document).ready(function()
{
    $(function()
    {
        $('.search input').focus( function()
        {
            $('.search #txtsearch').removeClass('inactive');
            if ($('.search #txtsearch').val() == "search")
            {
                $('.search #txtsearch').val("");
            }
            $('.search').css( { backgroundPosition: '0 0' } );
            return false;
        });
        $('.search input').blur( function()
        {
            $('.search #txtsearch').addClass('inactive');
            if ($('.search #txtsearch').val() == "")
            {
                $('.search #txtsearch').val("search");
            }
            $('.search').css( { backgroundPosition: '0 100%' } );
            return false;
        });


        var boolProductExpanded = false;
        var boolProductChanging = false;
        var SliderItems = 0;
        var SliderPos = 1;
        var ProductShow = 0;
        
        function ProductShowMore()
        {
            if ($.browser.msie === false)
            {
                $('.product .panel .panelclose').fadeIn();
            } else {
                $('.product .panel .panelclose').show();
            }
            $('.product .panel .thumbs').fadeIn();
            $('.product .panel .goleft').fadeIn();
            $('.product .panel .goright').fadeIn();
            $('.product .panel .seealsos').fadeIn();
            $('.product .panel h2').fadeIn();
            $('.product .panel .description').css({ overflow: "auto" });
            //$('.product .buttons').show();
            //$('.product .buttons').animate({ height: '45px'}, 375, 'swing');
            ThumbnailArrows();
            $('.advice_small').show();

            boolProductExpanded = true;
            boolProductChanging = false;
            ProductShow = 0;
        }
        function ProductHideMore()
        {
            $('.product .panel .panelclose').hide();
            $('.product .panel .thumbs').hide();
            $('.product .panel .goleft').hide();
            $('.product .panel .goright').hide();
            $('.product .panel .seealsos').hide();
            $('.product .panel h2').hide();
            $('.product .panel .description').css({ overflow: "hidden" });
            //$('.product .buttons').css({ height: "0px" });
            boolProductChanging = false;
            boolProductExpanded = false;
        }
        function ProductGrow()
        {
            if (boolProductExpanded === false || boolProductChanging === false)
            {
                boolProductChanging = true;
                $('.product').animate(
                {
                    paddingLeft: '20px',
                    width:'925px'
                }, 375, 'swing', function () { ProductShowMore(); } );
                $('.buttons').animate(
                {
                    marginLeft: '0'
                }, 375, 'swing');
            }
        }
        function ProductShrink()
        {
            if (ProductShow === 0)
            {
                if (boolProductExpanded === true || boolProductChanging === false)
                {
                    boolProductChanging = true;
                    if ($.browser.msie === false)
                    {
                        $('.product .panel .thumbs').fadeOut();
                        $('.product .panel .panelclose').fadeOut();
                        $('.product .panel .goleft').fadeOut();
                        $('.product .panel .seealsos').fadeOut();
                        $('.product .panel .goright').fadeOut();
                        $('.product .panel .description').css({ overflow: "hidden" });
                        $('.product .panel h2').fadeOut();
                    } else {
                        $('.product .panel .thumbs').hide();
                        $('.product .panel .panelclose').hide();
                        $('.product .panel .goleft').hide();
                        $('.product .panel .seealsos').hide();
                        $('.product .panel .goright').hide();
                        $('.product .panel .description').css({ overflow: "hidden" });
                        $('.product .panel h2').hide();
                    }
                        

                    $('.product').animate({ paddingLeft: '600px', width:'345px' }, 375, 'swing', function () { ProductHideMore(); } );
                    $('.product .buttons').animate({ marginLeft: '580px'}, 375, 'swing');
                }
            }
        }
        /*
        if (parseInt($('.wrap').height(), 10) > parseInt($('.description').height(), 10))
        {
            var pWidth = parseInt($('.product .panel').width(), 10);
            var pLeft = parseInt($('.product .panel').css('paddingLeft'), 10);
            $('.product .panel').width( (pWidth+100) + 'px');
            $('.product .panel').css( { paddingLeft: (pLeft-100) + 'px' } );
            $('.product .panel .description').width( (pWidth+100) + 'px');
        }
        */
		$('.product .panel').mouseenter(function () {
			if ($('.product .panel .panelclose:visible').length !== 0 || ProductShow === 1) {
				return;
			}
			var intTop = parseInt($('.product .panel').offset().top, 10);
			var intLeft = parseInt($('.product .panel').offset().left, 10);
			var intWidth = parseInt($('.product .panel').outerWidth(), 10);
			var intHeight = parseInt($('.product .panel').outerHeight() + $('.product .buttons').outerHeight(), 10);
			if ( $('#cover').length === 0 ) {
				$('body').append("<div id='cover'><div class='inside'><a href='/' id='btnshowdetails'>Show Details</a><br /><a href='/' id='btnshowpicture'>Show Picture</a></div></div>");
			}
			$('#cover').css( {
				position: 'absolute',
				top: intTop,
				left: intLeft,
				width: intWidth,
				height: intHeight,
				display: 'block'
			}).mouseleave(function () {	
				$(this).remove();
			});
			$('#btnshowdetails').click( function () {
				$('#cover').remove();
				var intThumbs = parseInt($('.thumb').length, 10);
				var intRelated = parseInt($('#seealsos').length, 10);
				if (intThumbs !== 0 || intRelated !== 0)
				{
					ProductShow = 1;
					ProductGrow();
				}
				return false;
			});
			$('#btnshowpicture').click( function () {
				$('#cover').remove();
				$('.menu').hide();
				$('.product').hide();
				$('.search').hide();
				if ( $('.pictureclose').length === 0) {
					$('.container').append("<div class='pictureclose'></div>");
				}
				$('.pictureclose').click( function () {
					$('.pictureclose').remove();
					$('.menu').show();
					$('.product').show();
					$('.search').show();
				});
				return false;
			});
		});
		
        /*
		$('.product .panel2').mouseenter(function ()
        {
            var intThumbs = parseInt($('.thumb').length, 10);
            var intRelated = parseInt($('#seealsos').length, 10);
            if (intThumbs !== 0 || intRelated !== 0)
            {
                ProductShow = 1;
                ProductGrow();
            }
        });
		*/
        $('.panelclose').click( function ()
        {
            if (ProductShow != 1)
            {
                ProductShow = 0;
                ProductShrink();
                $('.advice_small').hide();
            }
        });
        /*
        if ($('.buttons a').length > 0)
        {
            $('.product .buttons').animate( { height: '45px' }, 50);
        }
        */
        
        $('ul.dropdown li').hover(function()
        {
            $(this).addClass('hover');
            $('.sub_menu',this).css('visibility', 'visible');
        }, function() {
            $(this).removeClass('hover');
            $('.sub_menu',this).css('visibility', 'hidden');
        });

        $('ul.dropdown li .sub_menu').each(function(i)
        {
            var a = $(this).parent().find('a').width();
            var d = $(this).parent().find('.sub_menu').width();
            if ((d-4)<a)
            {
                $(this).parent().find('.sub_menu').width(a + 4);
            }
        });
        if ($('ul.dropdown li.wide ul').length > 1)
        {
            $('ul.dropdown li.wide ul').css( { marginBottom: '1em' } );
            $('ul.dropdown li.wide ul:last-child').css( { marginBottom: '1em' } );
        }
        /*
        $('ul.dropdown li.wide .sub_menu').each(function(i)
        {
            var highest = 0;
            $(this).find('ul').each(function(j)
            {
                if ($(this).height() > highest)
                {
                    highest = $(this).height();
                }
            });
            $('ul.dropdown li.wide .sub_menu ul').height(highest);
        });
        */
        function ThumbnailArrows()
        {
            if (SliderItems > 1 && SliderPos != 1)
            {
                $('.goleft').show();
            } else {
                $('.goleft').hide();
            }
            if (SliderItems > 1 && SliderItems == ((SliderPos-1)+5))
            {
                $('.goright').hide();
            } else {
                $('.goright').show();
            }
        }
        function SliderGoLeft()
        {
            if (SliderPos != 1)
            {
                SliderPos = SliderPos - 1;
                $('.slider').animate({ left: '-' + ((SliderPos-1)*105) + 'px' }, 250, 'swing' );
            }
            ThumbnailArrows();
        }
        function SliderGoRight()
        {
            if (SliderItems != ((SliderPos-1)+5))
            {
                SliderPos = SliderPos + 1;
                $('.slider').animate({ left: '-' + ((SliderPos-1)*105) + 'px' }, 250, 'swing' );
            }
            ThumbnailArrows();
        }
        $('.goleft').click( function()
        {
            SliderGoLeft();
            return false;
        });
        $('.goright').click( function()
        {
            SliderGoRight();
            return false;
        });
        $('.slider').mousewheel(function(objEvent, intDelta)
        {
            if (intDelta > 0)
            {
                SliderGoRight();
            } else if (intDelta < 0) {
                SliderGoLeft();
            }
        });
        
        /* change width of gallery slider */
        SliderItems = $('.slider .thumb').length;
        $('.slider').width(SliderItems * 105);
        //$('.buttons').height(0);
        if ($('.slider .thumb').length === 0)
        {
            $('.slider').remove();
            $('.thumbs').remove();
            $('.goleft').remove();
            $('.goright').remove();
            $('h2.gallery').remove();
            $('.seealsos').css ( { height : '380px' } );
        }

        function updateSlideshow(json)
        {
            $('.slideshow').crossSlide(
            {
                sleep: json.sleep,
                fade: json.fade
            }, json.slide);
        }
        
        if ($('.slideshow').length > 0)
        {
            $.getJSON('/_dynamic/slideshow.txt', { slideshow: 0 }, function(json)
            {
                $('.slideshow').append( "<img src='" + json.slide[0].src + "' />" );
                $.defer(100, updateSlideshow(json));                
            });
        }

        if ($('.description').length > 0)
        {
            var h = parseInt($('.description').css('height'), 10);
            var ht = parseInt($('h1').position().top, 10);
            var dt = parseInt($('.description').position().top, 10);
            h = h - (dt - ht);
            h = h + 30;
            $('.description').css('height', h + 'px');
        }

        if ($(".slider a").length > 0)
        {
            $(".slider a").overlay(
            {
                target: '#gallery'
            }).gallery(
            {
                speed: 800
            });
        }

        $('#btnWishlistRemove').live( 'click', function ()
        {
            var strProductID = $('#pageid').val();
            strProductID = strProductID.toString();
            var id = WishlistExists(strProductID);
            Delete_Cookie( 'wli' + id, '/', '' );
            
            WishListRemove();
            return false;
        });
        $('#btnWishlistAdd').live( 'click', function ()
        {
            var strProductID = $('#pageid').val();
            strProductID = strProductID.toString();
            var intWishListQuantity = 0;
            var intWishListItemID = 0;
            var boolExists = false;
            var strCompare = "";
            if (Get_Cookie('wlt'))
            {
                intWishListQuantity = Get_Cookie('wlt');
            }
            intWishListQuantity = parseInt(intWishListQuantity, 10);
            var i = 0;
            for (i=1;i<=intWishListQuantity;i++)
            {
                strCompare = Get_Cookie('wli' + i);
                if (strCompare !== null)
                {
                    strCompare = strCompare.toString();
                    if (strCompare === strProductID)
                    {
                        boolExists = true;
                        intWishListItemID = i;
                    }
                }
            }
            if (boolExists === false)
            {
                intWishListQuantity = intWishListQuantity + 1;
                Set_Cookie( 'wlt', intWishListQuantity, '', '/', '', '' );
                intWishListItemID = intWishListQuantity;
            }
            Set_Cookie( 'wli' + intWishListItemID, strProductID, '', '/', '', '' );
            
            WishListAdd();
            return false;
        });

        function WishListAdd()
        {
            var intTargetX = parseInt($('#btnWishList').offset().left, 10);
            var intTargetY = parseInt($('#btnWishList').offset().top, 10);
            var intTargetW = parseInt($('#btnWishList').width(), 10);
            var intTargetH = parseInt($('#btnWishList').height(), 10);
            var intSourceX = parseInt($('#btnWishlistAdd').offset().left, 10);
            var intSourceY = parseInt($('#btnWishlistAdd').offset().top, 10);
            var intSourceW = parseInt($('#btnWishlistAdd').width(), 10);
            var intSourceH = parseInt($('#btnWishlistAdd').height(), 10);

            $('.wishlistbox').remove();
            $('body').append("<div class='wishlistbox'></div>");
            
            $('.wishlistbox').css(
            {
                position: 'absolute',
                left: (intSourceX) + 'px',
                top: (intSourceY) + 'px',
                width: (intSourceW)+ 'px',
                height: (intSourceH) + 'px',
                display: 'block'
            });
            
            $('.wishlistbox').animate(
            { 
                left: intTargetX + 'px',
                top: intTargetY + 'px',
                width: intTargetW + 'px',
                height: intTargetH + 'px',
                opacity: 0.2
            }, 500, function ()
            {
                $('.wishlistbox').remove();
                $('#btnWishList').pulse({
                    opacity: [0,1]
                }, {
                    duration: 100, // duration of EACH individual animation
                    times: 3, // Will go three times through the pulse array [0,1]
                    easing: 'linear', // easing function for each individual animation
                    complete: function() { }
                });
            } );
            
            $('#btnWishlistAdd').text('Remove from Wish List');
            $('#btnWishlistAdd').attr('id', 'btnWishlistRemove');
        }
        
        function WishListRemove()
        {
            var intTargetX = parseInt($('#btnWishList').offset().left, 10);
            var intTargetY = parseInt($('#btnWishList').offset().top, 10);
            var intTargetW = parseInt($('#btnWishList').width(), 10);
            var intTargetH = parseInt($('#btnWishList').height(), 10);
            var intSourceX = parseInt($('#btnWishlistRemove').offset().left, 10);
            var intSourceY = parseInt($('#btnWishlistRemove').offset().top, 10);
            var intSourceW = parseInt($('#btnWishlistRemove').width(), 10);
            var intSourceH = parseInt($('#btnWishlistRemove').height(), 10);
            
            $('.wishlistbox').remove();
            $('body').append("<div class='wishlistbox'></div>");
            
            $('.wishlistbox').css(
            {
                position: 'absolute',
                left: intTargetX + 'px',
                top: intTargetY + 'px',
                width: intTargetW + 'px',
                height: intTargetH + 'px',
                display: 'block'
            });
            
            $('.wishlistbox').animate(
            { 
                left: (intSourceX) + 'px',
                top: (intSourceY) + 'px',
                width: (intSourceW)+ 'px',
                height: (intSourceH) + 'px',
                opacity: 0.2
            }, 500, function ()
            {
                $('.wishlistbox').remove();
                $('#btnWishlistRemove').text('Add to Wish List');
                $('#btnWishlistRemove').attr('id', 'btnWishlistAdd');
                $('#btnWishlistAdd').pulse({
                    opacity: [0,1]
                }, {
                    duration: 100, // duration of EACH individual animation
                    times: 3, // Will go three times through the pulse array [0,1]
                    easing: 'linear', // easing function for each individual animation
                    complete: function() { }
                });
            } );
            
        }

        $('.btnWishlistRemove').click( function()
        {
            var id = $(this).attr('id');
            id = id.replace(/wl/gi, "");
            id = id.split(':');

            var answer = confirm("Do you want to remove this product from your wish list?");
            if (answer){
                $('#wli' + id[0]).remove();
                Delete_Cookie( 'wli' + id[1], '/', '' );
            }

            return false;
        });
        
        
        function WishlistExists(id)
        {
            var intWishListQuantity = 0;
            var intWishListItemID = 0;
            var boolExists = false;
            var strCompare = "";
            if (Get_Cookie('wlt'))
            {
                intWishListQuantity = Get_Cookie('wlt');
            }
            intWishListQuantity = parseInt(intWishListQuantity, 10);
            var i = 0;
            for (i=1;i<=intWishListQuantity;i++)
            {
                strCompare = Get_Cookie('wli' + i);
                if (strCompare !== null)
                {
                    strCompare = strCompare.toString();
                    if (strCompare === id)
                    {
                        boolExists = true;
                        intWishListItemID = i;
                    }
                }
            }
            
            return intWishListItemID;
        }
        
        if ($('#btnWishlistAdd').length > 0)
        {
            if (WishlistExists($('#pageid').val()) != "0")
            {
                $('#btnWishlistAdd').text('Remove from Wish List');
                $('#btnWishlistAdd').attr('id', 'btnWishlistRemove');
            }
        }
        
        if ($.browser.msie === true)
        {
            if (parseInt($.browser.version, 10) === 7)
            {
                var csswidth = 0;
                $('.menu ul.dropdown > li').each( function (i)
                {
                    csswidth = parseInt($(this).find('.sub_menu').width(), 10);
                    $(this).find('.sub_menu').css( { width: (csswidth+10) + 'px' } );
                    $(this).find('.sub_menu ul').css( { width: csswidth + 'px' } );            
                });
            }
        }
        
        var agent=navigator.userAgent.toLowerCase();
        var is_iphone = (agent.indexOf('iphone')!=-1);
        //is_iphone = 1;
        if (is_iphone)
        {
            var boolShow = false;
            if ($('.container .content').length > 0 || $('.container .product').length > 0)
            {
                boolShow = true;
            }
            if ($('.container .nodynamic').length > 0)
            {
                boolShow = false;
            }
            //boolShow === true;
            if (boolShow === true)
            {
                if ($('.container .content').length > 0)
                {
                    $('.container').append("<div class='advice'>Use two fingers at the same time to scroll the collections list.</div>");        
                }
                if ($('.container .product').length > 0)
                {
                    $('.container').append("<div class='advice_small'>Use two fingers at the same time to scroll the content areas.</div>");        
                    $('.advice_small').hide();
                }
            }
            var link = $('.buttons a').attr('href');
            link = link.replace("#", "?");
            $('.buttons a').attr('href', link);
        }
    });
    
    document.addEventListener('touchmove', function(e){ e.preventDefault(); });
	$('.content').attr('id','content');
	myScroll = new iScroll('content');


});

