/*** NOTE: This definition of createDelegate can be removed once NewUtility.js is incorporated into all pages ***/
/**
 * Create a delegate (function) that sets the scope to a requested object.
 * Can be called directly on any function.  Creates a function that is automatically scoped
 * to obj so that the <b>this</b> var inside the function points to obj.<br />
 * This is a more useful version than the MS Toolkit's Function.createDelegate, which doesn't allow
 * extra parms to be passed.
 * @param {Object} [scope=window] object for which the scope is set.
 * @param {Array} [args=args passed by caller] override arguments for the call.
 * @param {Boolean|Number} [appendArgs=false] true to append to caller args instead of overriding, or
 * a if a number, the args are inserted at the specified position.
 * @returns {Function} The new function
 * @example
<code>
doSomething.createDelegate(this, ['foo', 'bar']);
...
doSomething();
...
function doSomething() {
	// arguments =['foo', 'bar'] here
}
// OR
doSomething.createDelegate(this, ['foo', 'bar'], true);
...
doSomething(false, 'hello');
...
function doSomething() {
	// arguments = [false, 'hello', 'foo', 'bar'] here
}
</code>
 */
Function.prototype.createDelegate = function(scope, args, appendArgs) {
    var method = this;
    return function() {
        var callArgs = args || arguments;
        if (appendArgs === true) {
            callArgs = Array.prototype.slice.call(arguments, 0);
            callArgs = callArgs.concat(args);
        } else if (typeof appendArgs == 'number') {
            callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
            var applyArgs = [appendArgs, 0].concat(args); // create method call params
            Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
        }
        return method.apply(scope || window, callArgs);
    };
};

jQuery(function($){
	jQuery.fn.imgZoomV2 = function(settings){
		settings = jQuery.extend({// Default settings...
			container:  'body',
			src:		'img/fullsize.jpg',
			hideIt:		false
		}, settings);

		//Array of images which are zoom-able.
		var targets = [];

		var zoomCt = $(settings.container);

		var onHoverIn = function(shade, helper, zoomed) {
			shade.fadeIn(200);
			helper.fadeIn(200);
			zoomed.fadeIn(200);
			if (settings.hideIt) {
				zoomCt.show();
			}
		};
		var onHoverOut = function(shade, helper, zoomed) {
			shade.fadeOut(200);
			helper.fadeOut(200);
			zoomed.fadeOut(200);
			if (settings.hideIt) {
				zoomCt.hide();
			}
		};

		/**
		 * Returns an array of images that will be operated on.
		 * @param {HTMLElement} el if the element is an image it will be added to the array and returned.
		 * If the element is not an image, it will be searched for child images.
		 * @returns {Array}
		 */
		var getImages = function(el) {
			var set = [];
			if ($(el).is('img')) {
				set.push(el);
			}
			else {
				$(el).find('img').each(function(i, img) {
					set.push(img);
				});
			}

			return set;
		};

       /*
         * Try to cleanup some of things we've created to minimize the IE6 leaks.
         * Called on window.unload
         */
        var destroy = function() {
			//remove the container that holds the zoomed image
			zoomCt.children('.zzz_zoomed').remove()
			//remove the image shadow and magnifier
			$(targets).next('.zzz_shade').remove();
			$(targets).next('.zzz_imghelper').remove();
        };

        $(window).unload(destroy);

		return this.each(function(i, el) {
			//Build array containing the images (or images that are children of el)
			targets = getImages(el);
		//Code to check for jewellery product
			
			var vcsVertical = $('input#vcsVertical').attr('value');
			var storeIdReq = $('input#storeIdReq').attr('value');
			//alert('storeId '+storeIdReq);
			//alert('vertical '+vcsVertical);
             if (typeof storeIdReq != 'undefined' && (storeIdReq != 10153 || storeIdReq != 10151) && vcsVertical != 'Jewelry'){
			

			$(targets).each(function(i, el) {
				var img = $(el),
					zoomedImg = new Image(),
					shade, helper, zoomed,
					imgCt = img.wrap('<div class="zzz_imgzoom"/>').parent();

				imgCt.css({
					width:		img.width(),
					height:		img.height(),
					overflow:	'hidden',
					position:	'relative'
				});

				zoomCt.css({
					position:	'relative',
					overflow:	'hidden'
				});

				//Add the overlay which will blur the image when zooming
				shade = $('<div class="zzz_shade"/>').css({
					width:		imgCt.width(),
					height:		imgCt.height(),
					display:	'none',
					position:	'absolute',
					top:		0,
					left:		0,
					background:	'url(img/loading.gif) no-repeat center center #fff',
					opacity:	0.75,
					filter:		'alpha(opacity=75)'
				}).appendTo(imgCt);

				//Add the magnifying sliding div
				helper = $('<div class="zzz_imghelper"/>').css({
					border:		'1px solid #fff',
					background:	'url(' + img.attr('src') + ') no-repeat -1px -1px #fff',
					display:	'none',
					position:	'absolute',
					top:		0,
					left:		0
				}).appendTo(imgCt);

				//Add the big image
				zoomed = $('<div class="zzz_zoomed"/>').hide().css({
					overflow:	'hidden',
					background:	'url(img/loading.gif) center center no-repeat #fff',
					position:	'absolute',
					height:		zoomCt.height(),
					width:		zoomCt.width(),
					top:		zoomCt.css('padding-top'),
					left:		zoomCt.css('padding-left')
				}).appendTo(zoomCt);

				zoomedImg.onload = function() {
					var scaleFactor = {
						x:(zoomedImg.width/img.width()),
						y:(zoomedImg.height/img.height())
					};

					helper.css({
						width:Math.round(zoomCt.width()/scaleFactor.x) + 'px',
						height:Math.round(zoomCt.height()/scaleFactor.y) + 'px'}
					);
					var maxH = img.height()- helper.height(),
						maxW = img.width()- helper.width(),
						helperHalf = {
							width: (helper.width()/2),
							height: (helper.height()/2)
						};

					zoomed.css({
						background:	'url(' + this.src + ') no-repeat 0 0 #fff'
					});
					shade.css({
						backgroundImage:'none',
						opacity:0.75,
						filter:'alpha(opacity=75)',
						background:'#ccc'
					});

					imgCt.unbind().hover(
						onHoverIn.createDelegate(this, [shade, helper, zoomed]),
						onHoverOut.createDelegate(this, [shade, helper, zoomed])).
						mousemove(function(e) {
							var top = e.pageY - img.offset().top - helperHalf.height,
								left = e.pageX - img.offset().left - helperHalf.width,
								nleft = left > maxW ? maxW : left < 0 ? 0 : left,
								ntop = top > maxH ? maxH : top < 0 ? 0 : top;

							zoomed.css({
								backgroundPosition: '-' + (nleft*scaleFactor.x) + 'px -' + (ntop*scaleFactor.y) + 'px'
							});
							helper.css({
								top:	ntop,
								left:	nleft,
								backgroundPosition: '-' + (nleft+1) + 'px -' + (ntop+1) + 'px'
							});
						});
					};

				zoomedImg.src = settings.src;
			});
		   };
		});
	};
});
