var globalSettings = {};
var globalUserInfo=null;
document.getElementsByTagName('html')[0].className = 'js';

function preLoadImages(imgArray) {
	$(imgArray).each(function (index) {
		$('<img src="/lasoo/v2/images/' + imgArray[index] + '" />');
	});
}

function fixIE6MinWidth() {
	$('.panel-tabs-primary .panel-header li a span').each(function () {
		if ($(this).width() < 83) {
			$(this).width(83);
		}
	})
}

function navigationSetLocation() {
	$('#header .module-location .nav-change-location a').click(function() {
		$('#header .module-location dt').hide();
		$('#header .module-find-store').hide();
		$('#header .module-location-change').show();
		return false;
	});
	$('#header .module-location .nav-find-store a').click(function() {
		$('#header .module-location dt').hide();
		$('#header .module-location-change').hide();
		$('#header .module-find-store').show();
		return false;
	});
}

function featuredOffersGetId (panelScroller) {
	return $(panelScroller).attr('id').replace('panel-scroller-', '');
}

function featuredOffersInit() {
	if ($('.panel-scroller').size() > 0) {
		
		//Setup Global Variable
		
		globalSettings.featuredOffers = new Array();
		
		$('.panel-scroller').each(function (panelIndex) {
			
			$(this).attr('id', 'panel-scroller-' + panelIndex);
			
			//Get Default Values			
			var moduleCount = $(this).find('.panel-content .module').size();
			var moduleWidth = $(this).find('.panel-content .module:first').width();
			var panelContentID = $(this).attr('id');
			var panelContentInner = $(this).find('.panel-content-inner');
			var panelCurrentPosition = $(this).find('.panel-content-inner').css('left');
			
			//Set panel-inner width, catering for an extra 2 modules for cloned first and last
			$(panelContentInner).width((moduleCount + 2) * moduleWidth);
			
			$(this).find('.panel-footer').append(
				'<ul class="player-controls">' +
					'<li><a href="#" class="player-previous">Previous</a></li>' +
					'<li><a href="#" class="player-next">Next</a></li>' +
				'</ul>');
			
			//Add IDs to each module
			$(this).find('.panel-content .module').each(function (moduleIndex) {
				$(this).attr('id', 'panel-scroller-' + panelIndex + '-' + moduleIndex);
				var classActive = '';
				if (moduleIndex == 0) {
					classActive = ' class="player-active" ';
				}
				$(this).parent().parent().siblings('panel-footer').children('.player-controls li:last').before('<li><a href="#panel-scroller-' + panelIndex + '-' + moduleIndex + '"'+ classActive +'>' + parseInt(moduleIndex+1) + '</a></li>');
			});
			
			//Clone and append the first & last modules for animating a carousel 
			$(this).find('.panel-content .module:last').clone(true).attr('id', 'panel-scroller-' + panelIndex + '-first').prependTo($(panelContentInner));			
			$(this).find('.panel-content .module:eq(1)').clone(true).attr('id', 'panel-scroller-' + panelIndex + '-last').appendTo($(panelContentInner));
			
			//Insert Global Variables
			globalSettings.featuredOffers[panelIndex] = new Array();
			globalSettings.featuredOffers[panelIndex]['moduleCount'] = moduleCount;
			globalSettings.featuredOffers[panelIndex]['panelContentInner'] = panelContentInner;
			globalSettings.featuredOffers[panelIndex]['moduleWidth'] = moduleWidth;
			globalSettings.featuredOffers[panelIndex]['panelCurrentPosition'] = panelCurrentPosition;
			globalSettings.featuredOffers[panelIndex]['panelIndex'] = 1;
			globalSettings.featuredOffers[panelIndex]['intervalID'] = new Array();
			
			if ($(this).hasClass('panel-scroller-auto')) {
				featuredOffersStart($(this));
			
				$(this).mouseover(function() {
					featuredOffersStop($(this));
				}).mouseout(function() {
					featuredOffersStart($(this));
				});
			}
			
			$(this).find('.player-controls .player-previous').click(function() {
				var controlParent = this;
				do {
					controlParent = $(controlParent).parent();
				} while (!$(controlParent).hasClass('panel-scroller'))
				
				featuredOffersAnimateTo(featuredOffersGetId($(controlParent)), 'prev');
				return false;
			});
			$(this).find('.player-controls .player-next').click(function() {
				var controlParent = this;
				do {
					controlParent = $(controlParent).parent();
				} while (!$(controlParent).hasClass('panel-scroller')) 
				
				featuredOffersAnimateTo(featuredOffersGetId($(controlParent)));
				return false;
			});
			$(this).find('.player-controls a:not(.player-next, .player-previous)').click(function () {
				var controlParent = this;
				do {
					controlParent = $(controlParent).parent();
				} while (!$(controlParent).hasClass('panel-scroller'))
					
				featuredOffersAnimateTo(featuredOffersGetId($(controlParent)), parseInt($(this).text()));
				return false;
			});
			
		})
	}
}

function featuredOffersStart(panelScroller) {
	var intervalID = setInterval(function () {
			featuredOffersAnimate(featuredOffersGetId($(panelScroller)))
		}, 5000);
	globalSettings.featuredOffers[featuredOffersGetId($(panelScroller))]['intervalID'].push(intervalID);
}

function featuredOffersStop(panelScroller) {
	while (globalSettings.featuredOffers[featuredOffersGetId($(panelScroller))]['intervalID'].length > 0) {
		clearInterval(globalSettings.featuredOffers[featuredOffersGetId($(panelScroller))]['intervalID'].pop());
	}
}

function featuredOffersAnimate(panelID, animateTo) {
	
	var panelNewPosition;
	
	panelNewPosition = globalSettings.featuredOffers[panelID]['panelIndex'] += 1;
	
	featuredOffersSetCurrent(panelID, panelNewPosition);
	
	var animateLeft = globalSettings.featuredOffers[panelID]['moduleWidth'] * panelNewPosition;

	$(globalSettings.featuredOffers[panelID]['panelContentInner'])
		.animate({left: '-' + animateLeft}, 1000, function () {
			if (panelNewPosition > globalSettings.featuredOffers[panelID]['moduleCount']) {
				$(globalSettings.featuredOffers[panelID]['panelContentInner']).css('left', '-' + globalSettings.featuredOffers[panelID]['moduleWidth'] + 'px');
				globalSettings.featuredOffers[panelID]['panelIndex'] = 1;
			}
		});
}

function featuredOffersAnimateTo(panelContentID, animateTo) {
	animateTo = typeof(animateTo) != 'undefined' ? animateTo : 'next';
	
	if (animateTo == 'next') {
		animateTo = globalSettings.featuredOffers[panelContentID]['panelIndex'] + 1;
		if (globalSettings.featuredOffers[panelContentID]['panelIndex'] > globalSettings.featuredOffers[panelContentID]['moduleCount']) {
			$(globalSettings.featuredOffers[panelContentID]['panelContentInner'] + ':animated').css('left', '-' + globalSettings.featuredOffers[panelContentID]['moduleWidth'] + 'px');
			animateTo = globalSettings.featuredOffers[panelContentID]['panelIndex'] = 2;
		}
			
	} else if (animateTo == 'prev') {
		animateTo = globalSettings.featuredOffers[panelContentID]['panelIndex'] - 1;
		if (globalSettings.featuredOffers[panelContentID]['panelIndex'] < 1) {
			$(globalSettings.featuredOffers[panelContentID]['panelContentInner'] + ':animated').css('left', '-' + globalSettings.featuredOffers[panelContentID]['moduleWidth'] * globalSettings.featuredOffers[panelContentID]['moduleCount'] + 'px');
			animateTo = globalSettings.featuredOffers[panelContentID]['panelIndex'] = globalSettings.featuredOffers[panelContentID]['moduleCount'] - 1;
		}
	}
	
	globalSettings.featuredOffers[panelContentID]['panelIndex'] = panelNewPosition = animateTo;
	
	featuredOffersSetCurrent(panelContentID, panelNewPosition);

	var animateLeft = globalSettings.featuredOffers[panelContentID]['moduleWidth'] * panelNewPosition;
	
	$(globalSettings.featuredOffers[panelContentID]['panelContentInner'])
	.stop()
	.animate({left: '-' + animateLeft}, 1000, function () {
		if (panelNewPosition > globalSettings.featuredOffers[panelContentID]['moduleCount']) {
			$(globalSettings.featuredOffers[panelContentID]['panelContentInner']).css('left', '-' + globalSettings.featuredOffers[panelContentID]['moduleWidth'] + 'px');
			globalSettings.featuredOffers[panelContentID]['panelIndex'] = 1;
		} else if (globalSettings.featuredOffers[panelContentID]['panelIndex'] < 1) {
			$(globalSettings.featuredOffers[panelContentID]['panelContentInner']).css('left', '-' + globalSettings.featuredOffers[panelContentID]['moduleWidth'] * globalSettings.featuredOffers[panelContentID]['moduleCount'] + 'px');
			globalSettings.featuredOffers[panelContentID]['panelIndex'] = globalSettings.featuredOffers[panelContentID]['moduleCount'];
		}
	});
}

function featuredOffersSetCurrent (panelID, panelNewPosition) {
	if (panelNewPosition > globalSettings.featuredOffers[panelID]['moduleCount'])
		panelNewPosition = 1;
	else if (panelNewPosition < 1)
		panelNewPosition = globalSettings.featuredOffers[panelID]['moduleCount'];
	
	$('#panel-scroller-' + panelID).find('.player-controls a').removeClass('player-active').eq(panelNewPosition).addClass('player-active');
}

//On Focus removes default value, On Blur if empty return to default
// Default value is in Title
function formDefaultValueInit (context) {
	$('.form-default-value', context).each(function() {
		var defaultValue = this.title;
//		if (!defaultValue) {
//			defaultValue=$(this).val();
//		}
		if ($(this).val() != defaultValue) {
			$(this).removeClass('form-default-value');
		}
		$(this).focus(function() {
			if ($(this).val() == defaultValue) {
				$(this).val('').removeClass('form-default-value');
			} else {
				this.select();
			}
		}).blur(function() {
			if ($(this).val() == '') {
				$(this).val(defaultValue).addClass('form-default-value');
			}
		})
	});
}
var modalPostCloseEvent=null;
function simpleModalInit() {
	$.extend($.modal.defaults, {
		onClose: function (dialog) {
			dialog.container.fadeOut(200, function () {
		    	dialog.overlay.fadeOut(200, function () {
		    		$.modal.close(); // must call this!
		    		if (modalPostCloseEvent) {
		    			modalPostCloseEvent();
		    			modalPostCloseEvent=null;
		    		}		    		
		    	});
		    });
		},
		onShow: function (dialog) {
			$(dialog.overlay).click(function () {
				$.modal.close();
			});
		},
		position: ['20%',]
	});
	
	$('.module-popup-dialog .button').click(function () {
		$.modal.close();
		return false;
	})
}
function closeModalPopop(callback) {
	if (callback) {
		modalPostCloseEvent = callback;
	}
	$.modal.close();
}
function closeModulePopupImme() {
	$.modal.impl.occb=true;
	$.modal.impl.close();	
}
function userLoginInit() {
	if ($('.block-user-login').size() > 0) {
		$('.block-user-login .panel').removeClass('panel-content-2').addClass('panel-secondary');
		$('.block-user-login .module').removeClass('module-content-2').addClass('module-secondary');
	}
	
	$('.module-user .user-sign-in a').click(function() {
		var destination = $(this).attr('href').split('#')[0];
		userLoginPopup(destination, false);
		return false;
	});
	// .module-user .user-why-join a
	$('.logged-out #account-bar .module-account-links a').click(function() {
		if ($(this).hasClass("direct-link")) {
			return true;
		} else {
			var destination = $(this).attr('href').split('#')[0];
			userLoginPopup(destination, true);
			return false;
		}
	});
}

function userLoginPopup(followinglink, showHeader) {
	if (showHeader == false)
		$('.block-user-login').addClass('block-user-whyjoin');
	else
		$('.block-user-login').removeClass('block-user-whyjoin');

	//$('#module-user-login-error').html("");
	document.moduleUserLoginForm.followinglink.value=followinglink?followinglink:"";

	$('.block-user-login').modal({'containerId': 'simplemodal-user-login'});
}
function whyJoinPopup() {
	$('.block-user-login').removeClass('block-user-whyjoin');
	$('.block-user-login').modal({'containerId': 'simplemodal-why-join'});
}
function alertsAddInit(parentClassName) {
	var preClassFilter = (parentClassName?"."+parentClassName+" ":"");
	$(preClassFilter+'a[href=#module-alerts-add]').click(function() {
		var form=document.moduleAddAlertForm;
		if (globalUserInfo) {
			form.email.readOnly=globalUserInfo.login
			if (globalUserInfo.login) {
				form.email.value=globalUserInfo.email;
			} else {
				form.email.value="";
			}
		} else {
			form.email.value="";
			form.email.readOnly=false;
		}
		$("#module-alerts-add-error").html("");
		$('#module-alerts-add').modal({'containerId': 'simplemodal-content-2'});
		return false;
	});
}

function shareInit() {
	$('.share-links').siblings('.icon-link-share').parent('li').hover(function () {
		$('.share-links', $(this)).show();
	}, function () {
		$('.share-links', $(this)).hide(); 
	});
	$('.shareToolbarHover .icon-link-share').click(function() {
		return false;
	})
	$('.shareToolbarHover').mouseover(function () {
		$('.shareToolbarHover .share').show();
	}).mouseout(function () {
		$('.shareToolbarHover .share').hide();
	})
}

function navigationInit () {
	preLoadImages(new Array('layout/sub-nav-bg.gif', 'layout/sub-nav-footer-bg.gif', 'layout/sub-nav-corner-left-bg.gif'));
	var hoverConfig = {    
	    sensitivity: 7,    
	    interval: 50,
	    over: function () {
			$(this).addClass('active');
			$('.sub-nav', $(this)).show();
			if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
				$('iframe', $(this)).height($('.sub-nav-content', $(this)).height()).show();
			}
		},    
	    timeout: 50,    
	    out: function () {
			$(this).removeClass('active');
			$('.sub-nav, iframe', $(this)).hide();
		}    
	};
	$('#navigation ol > li').hoverIntent( hoverConfig );
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
		$('#navigation .sub-nav').before('<iframe></iframe>');
	}
}
var addedHoverClassSet=[];
function addHoverClass(classArray) {
	var classArrayCopy = classArray.slice(0)
	for (var ii=classArray.length-1; ii>=0; ii--) {
		if (addedHoverClassSet[classArrayCopy[ii]]) {
			classArrayCopy.splice(ii, 1);
		}
	}
	$(classArrayCopy).each(function (index) {
		$('.' + classArray[index]).live('mouseover', function (event) {
			if (!eventWithinElement(event,this)) {
				$(this).addClass(classArray[index] + '-hover');
			}
		}).live('mouseout', function (event) {
			if (!eventWithinElement(event,this)) {
				$(this).removeClass(classArray[index] + '-hover');
			}
		});
	});
	for (var no in classArrayCopy) {
		addedHoverClassSet[classArrayCopy[no]]=true;
	}
}

function eventWithinElement(event,currentNode) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;
	// Traverse up the tree
	while ( parent && parent != currentNode ) {
		try { parent = parent.parentNode; }
		catch(e) { parent = currentNode; }
	}
	return parent == currentNode;
}
/*function addHoverClass(classArray) {
	$(classArray).each(function (index) {
		$('.' + classArray[index]).hover(function () {
			$(this).addClass(classArray[index] + '-hover');
		}, function () {
			$(this).removeClass(classArray[index] + '-hover');
		});
	});
}*/
var gridInitRunOnce=false;
function gridInit(parentClassName) {
	//preLoadImages(new Array('module/grid-bottom-bg.gif', 'module/grid-bottom-hover-bg.gif', 'module/full-width/grid-bottom-bg.gif', 'module/full-width/grid-bottom-hover-bg.gif'));
	var preClassFilter = (parentClassName?"."+parentClassName+" ":"");
	$(preClassFilter+'.module-grid-offer').each(function () {
		var placeholder = $('<div class="module-grid-offer-placeholder"></div>');//.width($(this).outerWidth(true)).height($(this).outerHeight(true));
		if ($(this).hasClass('module-grid-offer-related'))
				$(placeholder).addClass('module-grid-offer-related-placeholder');
		$(this).wrap(placeholder);
	});
	addHoverClass(Array('module-grid-offer', 'module-grid-offer-related', 'module-grid-catalogue'));
	if (!gridInitRunOnce) {
		gridInitRunOnce = true;
		$('.module-grid-offer-placeholder').live('mouseover', function () {
			$(this).css('z-index', '200');
		}).live('mouseout', function () {
			$(this).css('z-index', '10');
		});
	}
}

function lightboxInit(parentClassName) {
	var preClassFilter = (parentClassName?"."+parentClassName+" ":"");
	//initiates individual lightbox elements
	$(preClassFilter+'a[rel=lightbox]').each(function () {
		$(this).lightBox();
	});
	
	//finds groups of lightboxes
	var lightboxGroups = Array();
	
	$(preClassFilter+'a[rel!=lightbox][rel*=lightbox]').each( function () {
		
		var lightboxGroupExists = false;
		var groupName = '';
		if ($(this).attr('rel').search(' ') > 0) {
			groupName = $(this).attr('rel').substring(0,$(this).attr('rel').search(' '));
		} else
			groupName = $(this).attr('rel')
		
		for (var i = 0; i < lightboxGroups.length; i++) {
			
			if(lightboxGroups[i] == groupName)
				lightboxGroupExists = true;
		}
		
		if (!lightboxGroupExists) {
			$('a[rel*=' + groupName + ']').lightBox();
			lightboxGroups.push(groupName);
		}
	})
}

function catalogueInit() {
	var searchContext = $('#search');
	var searchOptions = '<div class="search-options"><span></span><ul>';
	var searchClass;
	$('option', searchContext).each(function (index) {
		if (index == 0 && !$(this).val()) {
			// no value node
		} else {
			if (index == 0) {
				searchClass = ' class="active"';
			} else {
				searchClass = '';
			}
			searchOptions += '<li><a href="#' + $(this).val() + '"' + searchClass + '>Search ' + $(this).text() + '</a></li>';
		}
	});
	searchOptions += '</ul></div>';
	$('#site-search-keyword', searchContext).after(searchOptions);
	
	$('.search-options a', searchContext).click(function () {
		$('#site-search-type option[value=' + $(this).attr('href').split('#')[1] + ']', searchContext).attr('selected', 'selected');
		$('.search-options a', searchContext).removeClass('active');
		$(this).addClass('active');
		if ($('#site-search-keyword', searchContext).hasClass('form-default-value')) {
			$('#site-search-keyword', searchContext).val($(this).text());
			$('#site-search-keyword', searchContext).attr("title",$(this).text());
			formDefaultValueInit(searchContext);
		}
		//$('.search-options', searchContext).removeClass('search-options-hover');
		return false;
	})
	
	$('.search-options', searchContext).hover(function () {
		$(this).addClass('search-options-hover');
	},function () {
		$(this).removeClass('search-options-hover');
	})

	if ($('.panel-refinement').size() > 0) {
		var refinementContext = $('.panel-refinement');
		$('.module-refinement .module-actions a', refinementContext).click(function() {
			if($(refinementContext).hasClass('panel-refinement-open')) {
				$('.panel-outer', refinementContext).stop().animate({left: "-196px"}, 500, function() {
					$(refinementContext).removeClass('panel-refinement-open');
				});
			} else {
				$('.panel-outer', refinementContext).stop().animate({left: "0px"}, 500).parent().addClass('panel-refinement-open');
			}
			return false
		})
		
	}
}

function cataloguePopupInit() {
	addHoverClass(Array('module-catalogue-popup'));
	$('.module-catalogue-popup .module-close a').click(function () {
		$('.module-catalogue-popup').hide();
	})
}

function scrollerMultiInit() {
	preLoadImages(new Array('module/catalogue/grid-bottom-hover-bg.gif', 'module/catalogue/grid-top-hover-bg.gif'));
	var scroller = $('.panel-scroller-multi')
	var viewableWidth = $('.panel-content', $(scroller)).width();
	var moduleWidth = $('.module', $(scroller)).eq(0).outerWidth(true);
	var noOfModules = $('.module', $(scroller)).size();
	var scrollerWidth = moduleWidth * noOfModules;
	var noOfViewableModules = parseInt(viewableWidth / moduleWidth);
	var totalViewableDisplays = Math.ceil(noOfModules / noOfViewableModules); 

	globalSettings.scrollerMultiPosition = -parseInt($('.panel-content-inner', scroller).css('left'));
	
	$(scroller).mouseover(function () {
		$('.panel-outer', $(this)).stop().animate({'height': '204px'}, 100)
	}).mouseout(function() {
		$('.panel-outer', $(this)).stop().animate({'height': '28px'}, 100)
	});
	
	$('.panel-footer .previous', $(scroller)).click(function () {
		scrollerMove(scroller, viewableWidth, scrollerWidth);
		return false;
	})
	$('.panel-footer .next', $(scroller)).click(function () {
		scrollerMove(scroller, -viewableWidth, scrollerWidth);
		return false;
	})
}

function scrollerMove(objScroller, animateAmount, scrollerWidth) {
	var animateTo = globalSettings.scrollerMultiPosition + animateAmount;
	if (animateTo <= 0 && animateTo > -scrollerWidth) {
		globalSettings.scrollerMultiPosition = animateTo;
		//console.log(animateTo);
		scrollerAnimate(objScroller, animateTo)
	}
		
}

function scrollerAnimate(objScroller, animateTo) {
	$('.panel-content-inner', $(objScroller)).stop().animate({'left': animateTo + 'px'}, 1000);
}

function galleryInit() {
	$('.module-gallery').each(function () {
		var galleryContext = $(this);
		$('.module-content img', galleryContext).each(function () {
			$(this).parent('a').click(function () {
				if ($('.module-media img', galleryContext).attr('src') != $(this).attr('href')) {
					$('.module-media', galleryContext).addClass('module-loading');
					$('.module-media img', galleryContext).load(function() {
						$(this).show().parent().removeClass('module-loading');
					})
					$('.module-media img', galleryContext).hide().attr('src', $(this).attr('href'));
				}
				return false;
			});
		});
	});
}

$(document).ready(function () {
	navigationSetLocation();
	fixIE6MinWidth();
	$('.panel-tabs .panel-content').tabs({fxAutoHeight: true});
	featuredOffersInit();
	formDefaultValueInit();
	simpleModalInit();
	userLoginInit();
	alertsAddInit();
	shareInit();
	
	addHoverClass(['module-listing']);
//	$('.module-listing').hover(function() {
//		$(this).addClass('module-listing-hover');
//	}, function() {
//		$(this).removeClass('module-listing-hover');
//	})
	
	navigationInit();
	gridInit();
	lightboxInit();
	catalogueInit();
	
	cataloguePopupInit();
	scrollerMultiInit();
	galleryInit();
	
	//$('.frontpage .content-1 .panel').draggable({ opacity: 0.7 });
	/*$('.frontpage .content-1 .block-content').sortable({
		connectWith: '.frontpage .content-1 .block-content',
		//placeholder: 'panel-placeholder',
		//snap: '.frontpage .content-1 .block-content',
		helper: 'clone',
		opacity: 0.7
	}).disableSelection();*/

	var searchForm = document.topsearchform;
	if (searchForm )
		searchForm.Ntt.focus();
	

})