function initTabs()
{
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

if (window.addEventListener)
{
	window.addEventListener("load", initTabs, false);
}
else if (window.attachEvent && !window.opera)
{
	window.attachEvent("onload", initTabs);
}

function openConsole( url, width, height )
{
    consoleWindow = window.open( url, "dstoreConsole", "left=30,top=30,width=" + width + ",height=" + height + ",scrollbars=yes,status=no,resizable" );
    consoleWindow.focus();
}

function urlEncodePlus(sourceString)
{
	encodedString = sourceString.replace(/ /g, "+");
	encodedString = escape(encodedString);
	encodedString = encodedString.replace('\/', '%252F');
	return encodedString;
}

jQuery.fn.gallSlide = function(_options){
	// defaults options	
	var _options = jQuery.extend({
		duration: 700,
		autoSlide: 5000
	},_options);

	return this.each(function(){
		var _hold = $(this);
		var _speed = _options.duration;
		var _timer = _options.autoSlide;
		var _wrap = _hold.find('ul');
		var _el = _hold.find('ul > li');
		var _next = _hold.parents('div.tab-content').find('a.link-next');
		var _prev = _hold.parents('div.tab-content').find('a.link-prev');
		var _count = _el.length-1;
		var _w = _el.outerWidth(true);
		var _wrapHolderW = Math.ceil(_wrap.parent().width()/_w);
		
		var _activeItem = 0;
		var _active = _activeItem;
		_el.removeClass('active');
		_el.eq(_activeItem).addClass('active');
		
		function scrollEl(){
			_wrap.eq(0).animate({
				marginLeft: -(_w * _active) + "px"
			}, {queue:false, duration: _speed});
			_el.removeClass('active');
			_el.eq(_activeItem).addClass('active');
			
		}
		_next.click(function(){
			_active = _activeItem;
			if(_activeItem < _count){
				_activeItem = _activeItem+1;
			}
			else{
				_activeItem = _count;
			}
			if (_active >= (_count - _wrapHolderW + 1)){
				_active = _count - _wrapHolderW + 1;
			}
			scrollEl();
			changeEl(_activeItem);
			return false;
		});
		
		_el.click(function(){
			_activeItem = _el.index($(this));
			_active = _activeItem - 1;
			if (_active >= (_count - _wrapHolderW + 1)){
				_active = _count - _wrapHolderW + 1;
			}
			else{
				if (_active < 0) _active = 0;
			}
			scrollEl();
			changeEl(_activeItem);
			return false;
		});
		
		_prev.click(function(){
			_active = _activeItem - 2;
			if(_activeItem > 0){
				_activeItem = _activeItem-1;
			}
			else{
				_activeItem = 0;
			}
			if (_active < 0) _active = 0;
			scrollEl();
			changeEl(_activeItem);
			return false;
		});
		
		
		var wait_time = 1500; // in ms
		var change_speed = 500; // in ms
		var _holder = _hold.parents('div.tab-content').find('div.gallery');
		var _t;
		var _f = true;
		var _list = _holder.find('ul.fader > li');
		var _btn = $('<ul class="paging"></ul>');
		_list.each(function(_i){
			_btn.append('<li><a href="#">'+(_i+1)+'</a></li>');
		});
		_btn = _hold.find('ul.switcher').find('a');
		var _a = _list.index(_list.filter('.active:eq(0)'));
		if(_a == -1) _a = 0;
		
		_list.removeClass('active').css('opacity', 0).css({visibility: 'hidden'}).eq(_a).addClass('active').css('opacity', 1).css({visibility: 'visible'});
		_list.eq(_a).css('opacity', 'auto');
		_btn.removeClass('active');
		_btn.eq(_a).parent('li').addClass('active');
		
		_btn.click(function(){
			changeEl(_btn.index(this));
		});
		
		function changeEl(_ind){
			if(_t) clearTimeout(_t);
			
			// _a is the currently active index. _ind is the one we're changing it to.
			if(_ind != _a){
				_list.eq(_a).animate({opacity: 0}, {queue:false, duration:change_speed, complete: function(){
					$(this).css({visibility: 'hidden'}).removeClass('active');
				}});
				_list.eq(_ind).css({visibility: 'visible'}).addClass('active').animate({opacity: 1}, {queue:false, duration:change_speed, complete:function(){
					$(this).css('opacity', 'auto');
					// Update the 'enlarge' link
					if ( _galleryProductId = _holder.closest('.tab-content').attr('galleryProductId') )
					{
						_holder.find('a.popupzoom').show().attr('href', '/?module=product&view=viewimage&id=' + _galleryProductId + '&imagenum='+(_ind + 1));
					}
					else
					{
						_holder.find('a.popupzoom').hide();
					}
					
				}});
				_btn.parent('li').removeClass('active');
				_btn.eq(_ind).parent('li').addClass('active');
				_a = _ind;
			}
		}
		
	});
}


$(document).ready(function(){
	initCart();
	initSlideHover();
	clearInputs();
	if($('.jqzoom').length != 0){
		 var options1 =
            {
                zoomWidth: 380,
                zoomHeight: 281,
				xOffset: 0,
                title: false
            }
            $(".jqzoom").jqzoom(options1);
	}
	colorChange();
	initDimensions();
	initSlider();
	$('div.gallery-holder').gallSlide({
		duration: 500
	});
	
	// Change popupzoom links to open in a resized popup window
	$('a.popupzoom').each(function(){
		var _pz = $(this);
		
		_pz.click(function(){
			popupwidth = $(this).attr('popupwidth') ? $(this).attr('popupwidth') : '440';
			popupheight = $(this).attr('popupheight') ? $(this).attr('popupheight') : '540';
			openConsole($(this).attr('href'), popupwidth, popupheight);
			return false;
		})
	});
	
	// Initialize the country dropdown
	$('a#change_country').click(function(){
		$(this).blur();
		$('#country_opt_wrapper').css('top', '2px');
		$('#country_options').slideDown('fast');
		return false;
	});
	
	$('#country_opt_wrapper').mouseleave(function(){
		$('#country_options').slideUp('fast', function(){
			$('#country_opt_wrapper').css('top', '-999px');
		});
		
	});
	
	// Start the country dropdown in the collapsed position
	$('#country_options').slideUp(1);
	
	// Set the onsubmit for search box to post
	$('form.search-form').attr('method', 'POST').submit(function(){
		$(this).attr('action', '/search/'+urlEncodePlus($(this).find('[name="search_term"]').val())+'/');
	});
});

// Function Cart
function initCart(){
	var _t;
	var change_speed = 600;
	var drop_hide_delay = 400;
	var _drop = $('a.bag').parent('li').find('div.drop');
	var _h = _drop.outerHeight();
	_drop.css('top', -(_h+200))
	
	$('a.bag').mouseenter(function(){
		_drop.find('ul.products > li').removeClass('active');
		cartSlideDown();
	}).mouseleave(function(){
		_t = setTimeout(function(){
			_drop.animate({top: -(_h+200)}, {queue:false, duration:change_speed});
		}, drop_hide_delay);
	});
	
	_drop.mouseenter(function(){
		if(_t) clearTimeout(_t);
	}).mouseleave(function(){
		_t = setTimeout(function(){
			_h = _drop.outerHeight();
			_drop.animate({top: -(_h+200)}, {queue:false, duration:change_speed});
		}, drop_hide_delay);
	});
	
	function cartSlideDown(){
		if(_t) clearTimeout(_t);
		_drop.animate({top: 0}, {queue:false, duration:change_speed});
	}
	
	// Initialize 'add to bag' buttons
	$('input.cart-btn').each(function(){
		$(this).click(function(){
			
			jQuery.ajax({
				type: "GET",
				global: false,
				dataType: "html",
				url: '/ajax/?module=trolley',
				data: 'action=add&'+$(this).closest('form').serialize(),
				success: function(msg){
					_ajaxDocument = $(msg);
					
					// Check for errors
					_error = _ajaxDocument.find('#error');
					
					// Remove any previous errors
					$('.size-form span.error').remove();
					$('.size-form select').removeClass('error');
					
					if ( _error.text() )
					{
						// Error - display message
						_error.find('.errorField').each(function(){
							dimensionRow = $('.size-form .dimensionSelect_'+$(this).text());
							
							dimensionRow.append('<span class="error">Please select a '+$(this).text()+'</span>');
							dimensionRow.find('select').addClass('error');
						});
					}
					else
					{
						// Update the trolley qty
						var _trolleyQty = _ajaxDocument.find('#trolleyQty');
						if ( _trolleyQty.text() )
						{
							_drop.parent('li').find('span.trolleyQty').text(_trolleyQty.text());
						}
						
						// Update the drop content with the ajax response
						var _newDropContent = _ajaxDocument.find('#newTrolley div.content');
						if ( _newDropContent.length )
						{
							_drop.find('div.content').replaceWith(_newDropContent);
							
							// Highlight the first item
							_drop.find('ul.products > li:first').addClass('active');
							
							// HSDS add: initialize the listeners on the updated trolley flyout
							initBagRemove();
						}
						
						_h = _drop.outerHeight();
						cartSlideDown();
						_t = setTimeout(function(){
							_drop.animate({top: -(_h+200)}, {queue:false, duration:change_speed});
						}, 3000);
					}
				},
				error: function(msg){
//					alert('Data get error!');
				}
			});
			
			return false;
		});
	});
	
	initBagRemove();
}

// Initialize remove buttons in bag flyout
function initBagRemove() {
	var _drop = $('a.bag').parent('li').find('div.drop');
	
	$('#header .top-nav a.close').each(function(){
		var _remove_btn = $(this);
		
		_remove_btn.click(function(){
			
			jQuery.ajax({
				type: "GET",
				global: false,
				dataType: "html",
				url: '/ajax/?module=trolley&action=remove&id=' + $(this).attr('trolleyid'),
				success: function(msg){
					var _ajaxDocument = $(msg);
					
					// Update the trolley qty
					_newTrolleyQty = _ajaxDocument.find('#trolleyQty').text();
					if ( !_newTrolleyQty )
					{
						_newTrolleyQty = '0';
					}
					_drop.parent('li').find('span.trolleyQty').text(_newTrolleyQty);
					
					// Update the drop content with the ajax response
					var _newDropContent = _ajaxDocument.find('#newTrolley div.content');
					_drop.find('div.content').replaceWith(_newDropContent);
					
					// HSDS add: initialize the listeners on the updated trolley flyout
					initBagRemove();

				},
				error: function(msg){
//					alert('Data get error!');
				}
			});
			
			// Fade out the item that we removed
			$(this).parent('div.holder').fadeOut(400);
			
			return false;
		});
	});
}


// color change swatch
function colorChange() {
	$('ul.color').each(function(){
		var _list = $(this);
		var _links = _list.find('a.color-tab');
		var _select = $('select.size');
		_links.each(function() {
			var _link = $(this);
			var _href = _link.attr('href');
			var _tab = $(_href);

			if (_link.hasClass('active')) 
				_tab.css({
					position: 'static',
					top: 0
				}).addClass('current');
			else {
				_tab.css({
					position: 'absolute',
					top: -9999
				}).removeClass('current');
			}

			_link.click(function(){
				_links.filter('.active').each(function(){
					$($(this).removeClass('active').attr('href')).css({
						position : 'absolute',
						top:-9999
					}).removeClass('current');
					$(this).parent('li').removeClass('active');
				});
				$(this).parent('li').addClass('active');
				
				_link.addClass('active');
				var _mas = _link.attr('rel');
				_mas = eval(_mas);
				_select.empty().append(_mas);
				_tab.addClass('current');
				_tab.css({
						position : 'static',
						top:0
					});
				return false;
			});
		});
	});
}

// change dimension
function initDimensions() {
	$('select.dimension').change(function(){
		var _selectedGalleryId = 'gallery-' + $(this).find('option:selected').attr('id');
		
		// Change to the corresponding gallery
		$('#sidebar .tab-content').each(function(){
			var _gallery = $(this);
			
			if (_gallery.attr('id') == _selectedGalleryId)
			{
				_gallery.addClass('current');
			}
			else
			{
				_gallery.removeClass('current');
			}
		});
	});
}

// Function clear inputs
function clearInputs(){
	$('input:text, input:password, textarea').each(function(){
		var _el = $(this);
		var _val = _el.attr('alt');
		
		if ( _val )
		{
			_el.bind('focus', function(){
				if(this.value == _val) this.value = '';
			}).bind('blur', function(){
				if(this.value == '') this.value = _val;
			});
		}
	});
}

// Init Slide Hover
function initSlideHover(){
	var _t = false;
	var _H = [];
		var _duration = 200; //in ms
		var h_class = 'hover';
		var _li = $('#nav > li');
		_li.each(function(){
			var _boxes = $(this).children('div.drop');
			var _boxH = _boxes.show().outerHeight(true);
			_H.push(_boxH);
			_boxes.height(0);
		});
		 _li.mouseenter(function(){
		 	var _i = _li.index($(this));
		 	var _f = true;
			$(this).addClass(h_class);
			var _box = $(this).children('div.drop');
			if (_box.length != 0 && $.browser.msie && $.browser.version < 7) {
				$('select').css('visibility', 'hidden');
			}
			if(_f){
				_box.animate({height:_H[_i]},  {queue:false, duration:_duration});
				_f = false;
			}
			if(_t){
				_t = clearTimeout();
			}
		}).mouseleave(function(){
			$('select').css('visibility', 'visible');
			$(this).removeClass(h_class);
			var _box = $(this).children('div.drop');
			_t = setTimeout(function(){
				_box.animate({height:0}, _duration, function(){
					_f = true;
				});
			}, 30)
		});
}

//Function Slider
function initSlider(){
	ieHover('ul.top-nav > li, #nav > li');
	$('div.preloader').find('div.preloader-bg').css('opacity', 0.6);
	$('div.slider-inner').each(function(){
		
		// Number of steps in the slider
		maxPoint = 200;
		
		// Logarithmic scale.
		logarithmScale = 2;
		
		// Get the maximum value for the slider
		sliderExtentMax = $(this).attr('slidemax');
		
		sliderLeftValue = $("span.min").html();
		sliderRightValue = $("span.max").html();
		
		// If the max value is lower than the number of steps, just use a linear progression
		if ( sliderExtentMax < maxPoint )
		{
			maxPoint = sliderExtentMax;
		}
		
		// Calculate the ratio that used to fit the values within the limits of the slide
		logToValueRatio = (sliderExtentMax - maxPoint) / Math.pow(maxPoint, logarithmScale);
		
		// Find the position of the slider that corresponds to this value
//		sliderLeftPoint  = Math.round(Math.pow(sliderLeftValue / logToValueRatio, 1/logarithmScale));
//		sliderRightPoint = Math.round(Math.pow(sliderRightValue / logToValueRatio, 1/logarithmScale));
		if (logToValueRatio > 0)
		{
			// Logarithmic
			sliderLeftPoint  = Math.round((Math.pow(( 4 * sliderLeftValue * logToValueRatio) + 1, 1/logarithmScale) - 1) / ( 2 * logToValueRatio));
			sliderRightPoint = Math.round((Math.pow(( 4 * sliderRightValue * logToValueRatio) + 1, 1/logarithmScale) - 1) / ( 2 * logToValueRatio));
		}
		else
		{
			// Linear
			sliderLeftPoint  = sliderLeftValue;
			sliderRightPoint = sliderRightValue;
		}
		
		$(this).slider({
			range: true,
			min: 0,
			max: maxPoint,
			step: 1,
			values: [sliderLeftPoint, sliderRightPoint],
			slide: function(event, ui) {
				if (logToValueRatio > 0)
				{
					// Logarithmic
					$("span.min").html(Math.round(Math.pow(ui.values[0], logarithmScale) * logToValueRatio + ui.values[0]));
					$("span.max").html(Math.round(Math.pow(ui.values[1], logarithmScale) * logToValueRatio + ui.values[1]));
				}
				else
				{
					// Linear
					$("span.min").html(ui.values[0]);
					$("span.max").html(ui.values[1]);
				}
			},
			change: function(event, ui) {
				
				$('div.preloader').fadeIn(200);
				
				jQuery.ajax({
					type: "GET",
					global: false,
					data: "pricestart="+$("span.min").html()+"&priceend="+$("span.max").html(),
					success: function(msg){
						$('div.preloader').hide();
						
						_ajaxDocument = $(msg);
						
						// Update products block on the page with the one from the ajax
						$('#product-ajax').html(_ajaxDocument.find('#product-ajax').html());
					},
					error: function(msg){
						alert('Ajax sent error!');
					}
				});
			}
		});
	});
}

// function ieHover
function ieHover(h_list, h_class){
	if($.browser.msie && $.browser.version < 7){
		if(!h_class) var h_class = 'hover';
		$(h_list).live('mouseover', function(){
			$(this).addClass(h_class);
		}).live('mouseout', function(){
			$(this).removeClass(h_class);
		});
	}
}
