var $JQ = jQuery.noConflict();
var animSpeed = 300;
var scrollSpeed = 300;
// cookie options
cookieOptions = {
hoursToLive: 100000
}

// cookie name
cookieName = 'sg_language';

//cookie set already overide
cookieOveride = 0;

$JQ(document).ready(function() {
	//SANDG.GENERIC.checkCookie();
	LIBRARY.prepopulateFieldsText('fieldPrepopulate');
	SANDG.GENERIC.activateSifr();
	SANDG.GENERIC.bindNav();
	SANDG.GENERIC.bindSlides();
	SANDG.GENERIC.bindTeam();
	SANDG.GENERIC.resizeBoxes();
	SANDG.GENERIC.rssConfirm();
	SANDG.FORMS.imposeMaxLength();
	SANDG.FORMS.bindUntickSearchForm();
	SANDG.FORMS.bindTickSearchForm();
	SANDG.FORMS.productMenuSearch();
	SANDG.PAGINATION.paginationAjaxLinks();
	GOOGLE.TRACKER.activateTracking();
	if($JQ('a.lightBox').length) { $JQ('a.lightBox').lightBox(); }
	SANDG.GENERIC.initPromo();
	
	//temp bind
	$JQ('#SMPenterYourself146').click(function(){
		
		window.location = '/category/fun-with-s-g/mother-pucker-competition';
	});
});

// *******************************************************************************************

SANDG = {
};

// *******************************************************************************************

SANDG.GENERIC = {
	checkCookie:function() {
	//set cookie
	//jaaulde.utils.cookies.set(cookieName, 'test');
	//jaaulde.utils.cookies.setOptions(cookieOptions);
	//get cookie
	//currentCookie = jaaulde.utils.cookies.get(cookieName);
	//alert(currentCookie)

	},
	
	initPromo: function() {
		if($JQ('#homePagePromoContent').length) {
			$JQ('#homePagePromoContent').lightBox().click();
			$JQ('#jquery-lightbox').remove();
			$JQ('<div id="homePagePromoPopup"></div>').insertAfter('#jquery-overlay');
			$JQ('#homePagePromoPopup').html($JQ('#homePagePromoContent').html());
			$JQ('#homePagePromoContent').remove();
			$JQ('#jquery-overlay').live('click', function() {
				$JQ('#homePagePromoPopup').remove();
			});
			$JQ('#homePagePromoPopup').live('click', function() {
				$JQ('#jquery-overlay').click();
			});
		}
	},
	
	activateSifr: function() {
		sIFR.replace(HelveticaNeueLT, {
			selector: '.teamMemberDetails h2.sifr',
			css: '.sIFR-root { color:#ffffff; text-transform:uppercase; font-size:20px; }',
			fitExactly: true,
			forceSingleLine: false,
			preventWrap: false,
			offsetTop: 3,
			tuneHeight: -3,
			wmode: 'transparent'
		});
		
		sIFR.replace(HelveticaNeueLT, {
			selector: '.teamMemberDetails h3.sifr',
			css: '.sIFR-root { color:#F5CED6; text-transform:uppercase; font-size:16px; }',
			fitExactly: true,
			forceSingleLine: false,
			preventWrap: false,
			offsetTop: 3,
			tuneHeight: -3,
			wmode: 'transparent'
		});
		
		sIFR.replace(HelveticaNeueLT, {
			selector: 'h1.sifr, h2.sifr',
			css: ['.sIFR-root { color:#F24470; text-transform:uppercase; font-size:20px; }',
				  'a { color:#E68A9E; cursor:pointer; text-decoration:none; }',
				  'a:hover { color:#F24470; cursor:pointer; text-decoration:none; }'],
			fitExactly: true,
			forceSingleLine: true,
			preventWrap: true,
			offsetTop: 3,
			tuneHeight: -3,
			wmode: 'transparent'
		});
	},
	
	bindSlides: function() {
		$JQ('a.button[rel], a.arrow[rel], a.viewAll[rel]').unbind('click').bind('click', function() {
			var linkObject = 		SANDG.GENERIC.getSlideVariables($JQ(this))[0];
			var boxObject = 		SANDG.GENERIC.getSlideVariables($JQ(this))[1];
			var scrollInvoke = 		true;
			var newLinkHtml = 		false;
			
			if(boxObject.css('visibility') === 'hidden') {
				if(linkObject.hasClass('buttonExclusive')) {
					SANDG.GENERIC.boxSlideUp(SANDG.GENERIC.getActiveElements(linkObject)[0], SANDG.GENERIC.getActiveElements(linkObject)[1], false);
				}
				
				if(linkObject.attr('rel').indexOf('allPostComments') > -1) {
					newLinkHtml = 'Hide';
				}
				
				if(linkObject.attr('rel').indexOf('formExpandingInside') > -1) {
					newLinkHtml = '<span>Close panel</span>';
				}
				
				SANDG.GENERIC.boxSlideDown(boxObject, linkObject, scrollInvoke, newLinkHtml);
			}
			else if(boxObject.css('visibility') === 'visible') {
				if(linkObject.attr('rel').indexOf('allPostComments') > -1) {
					newLinkHtml = 'View all';
				}
				
				if(linkObject.attr('rel').indexOf('formExpandingInside') > -1) {
					newLinkHtml = '<span>' + linkObject.attr("title") + '</span>';
				}
				
				SANDG.GENERIC.boxSlideUp(boxObject, linkObject, newLinkHtml);
			}
			return false;
		});
		
		if(location.hash.indexOf('#open') > -1) {
			$JQ('.boxHead a.buttonMultiple').click();
		}
	},
	
	bindTeam: function() {
		$JQ('.contentBoxTeam').unbind('click').bind('click', function() {
			var member = $JQ(this);
			var memberName = $JQ(this).attr('rel');
			var otherMembers = $JQ('.teamMembers .contentBoxTeam');
			$JQ('.teamMemberImage .faceActive').removeClass('faceActive');
			$JQ('.teamMemberImage .' + memberName).addClass('faceActive');
			$JQ('.teamMemberBlock .teamMemberDetailsActive').removeClass('teamMemberDetailsActive');
			$JQ('.teamMemberBlock .' + memberName).addClass('teamMemberDetailsActive');
			otherMembers.each(function() {
				$JQ(this).removeClass('contentBoxTeamActive');
			});
			member.addClass('contentBoxTeamActive');
			SANDG.GENERIC.scrollPage($JQ('.teamMemberBlock'));
		});
	},
	
	bindNav: function() {
		$JQ('.categoryNav ul > li').each(function() {
			if($JQ(this).children('ul').length > 0){
				$JQ(this).addClass('hasSub');
			}
		});
		
		$JQ('.categoryNav li.activeHasSub').each(function() {
			var this_cat=this.className.split(' ')[0].substring(4);
			if(this_cat!=document.getElementById('current-category').value){
				if(!$JQ('input:checked', this).length) {
					$JQ(this).removeClass('activeHasSub');
				}
			}
		});
		
		$JQ('.categoryNav ul > li > a').not('.showAll').unbind('click').bind('click', function(){
		   var parentItem = $JQ(this).parents('li');
			if(parentItem.hasClass('active')) {
				parentItem.removeClass('active');
				parentItem.removeClass('activeHasSub');
			}
			else {
				parentItem.addClass('active');
				parentItem.addClass('activeHasSub');
			}
			return false;
		});
		
		$JQ('.buttonRefine a').unbind('click').bind('click', function() {
			$JQ('.buttonRefine').click();
		});
	},
	
	getSlideVariables: function(link) {
		var linkObject = '';
		if(link.hasClass('buttonMultiple')) {
			linkObject = $JQ('.buttonMultiple');
		}
		else {
			linkObject = link;
		}
		var boxObject = $JQ('#'+linkObject.attr('rel'));
		return[linkObject, boxObject];
	},
	
	getActiveElements: function(linkObject) {
		var activeButton = $JQ('a.buttonActive', linkObject.parents('.expandableHead').siblings('.expandableHead'));
		var activeBox = $JQ('#' + activeButton.attr('rel'));
		return [activeBox, activeButton];
	},
	
	scrollPage: function(scrollPos) {
		$JQ('html, body').animate({
			scrollTop: scrollPos.offset().top
		}, scrollSpeed);
	},
	
	boxSlideDown: function(boxObject, linkObject, scrollPage, newLinkHtml) {
		boxObject.css({
			'display':		'none',
			'visibility':	'visible',
			'height':		'auto',
			'position':	 'relative'
		});
		linkObject.addClass('buttonActive');
		boxObject.slideDown(animSpeed, function() {
			if(newLinkHtml) {
				linkObject.html(newLinkHtml);
			}
			if(scrollPage) {
				SANDG.GENERIC.scrollPage(linkObject);
			}
		});
	},
	
	boxSlideUp: function(boxObject, linkObject, newLinkHtml) {
		boxObject.slideUp(animSpeed, function() {
			boxObject.css({
				'display':		'inline',
				'visibility':	'hidden',
				'height':		'0px',
				'position':	 'static'
			});
			if(newLinkHtml) {
				linkObject.html(newLinkHtml);
			}
			linkObject.removeClass('buttonActive');
		});
	},

	processFormErrors : function(errors, form){
		var _errorRow = $JQ(form).find("div.errorRow");
		
		if(_errorRow)
		{
			_errorRow.empty();
			
			for(var message in errors)
			{
				_errorRow.append("<p>" + errors[message] + ":&nbsp;<span class='highlighted'>" + message + "</span></p>");
			}
			
			_errorRow.show();
		}
	},
	
	showAjaxLoading : function(){
		console.log('ajax loading...');
		
	},
	
	/*resizeBoxes: function() {
		$JQ('.contentBoxSmall').each(function() {
			var rowHeight = 'auto';
			var boxHeight = LIBRARY.getTotalHeight($JQ(this));
			var descriptionHeight = 'auto';
			var readMoreHeight = 'auto';
			var boxContent = 'auto';
			var ieHack = 0;
			var isIE6 = $JQ.browser.msie && $JQ.browser.version.substr(0,1) < 7;
			
			if (isIE6) {
				ieHack = 7;
			}
			if ($JQ('.productDescription', this).length) {
				descriptionHeight = LIBRARY.getTotalHeight($JQ('.productDescription', this)) - 5 - ieHack;
			}
			if ($JQ('.readMore', this).length) {
				boxContent = LIBRARY.getTotalHeight($JQ('.boxContent', this)) - ieHack;
			}
			if ($JQ(this).parents('.boxRow').length) {
				rowHeight = LIBRARY.getTotalHeight($JQ(this).parents('.boxRow')) - 20;
			}
			if ($JQ('.productDescription', this).length && $JQ(this).parents('.boxRow').length) {
				if (isIE6) {
					$JQ('.productDescription', this).css('height', descriptionHeight + (rowHeight - boxHeight));
				}
				else {
					$JQ('.productDescription', this).css('min-height', descriptionHeight + (rowHeight - boxHeight));
				}
			}
			if ($JQ('.readMore', this).length && $JQ(this).parents('.boxRow').length) {
				if (isIE6) {
					$JQ('.boxContent', this).css('height',boxContent + (rowHeight - boxHeight));
				}
				else {
					$JQ('.boxContent', this).css('min-height',boxContent + (rowHeight - boxHeight));
				}
			}
		});
	},
	*/
	resizeBoxes: function() {
		$JQ('.boxRow').each(function() {
			$JQ('.contentBoxSmall',this).each(function() {
				var ieHack 				= 0;
				var isIE6 				= $JQ.browser.msie && $JQ.browser.version.substr(0,1) < 7;
				var ieHack 				= 7;
				var rowHeight 			= LIBRARY.getTotalHeight($JQ(this).parents('.boxRow')) - 20;
				var boxHeight 			= LIBRARY.getTotalHeight($JQ(this));
				if ($JQ('.productDescription', this).length) {
					var descriptionHeight = LIBRARY.getTotalHeight($JQ('.productDescription', this)) - 5;
				}
				if ($JQ('.boxContent', this).length) {
					var contentHeight = LIBRARY.getTotalHeight($JQ('.boxContent', this));
				}
				
				if ($JQ('.productDescription', this).length) {
					if (isIE6) {
						$JQ('.productDescription', this).css('height', descriptionHeight + (rowHeight - boxHeight) - ieHack);
					}
					else {
						$JQ('.productDescription', this).css('min-height', descriptionHeight + (rowHeight - boxHeight));
					}
				}
				
				if ($JQ('.readMore', this).length) {
					if (isIE6) {
						$JQ('.boxContent', this).css('height',contentHeight + (rowHeight - boxHeight) - ieHack);
					}
					else {
						$JQ('.boxContent', this).css('min-height',contentHeight + (rowHeight - boxHeight));
					}
				}
			});
		});
	},
	
	rssConfirm: function() {
		$JQ('.boxGossip li a').unbind('click').bind('click', function() {
			if (SANDG.GENERIC.showConfirmBox('Soap & Glory Limited is not responsible for the content of external internet sites.') != true) {
				return false;
			}
		});
	},
	
	showConfirmBox: function(confirmText) {
		return confirm(confirmText);
	}
	
};

SANDG.AJAX = {
	showLoading: function(){
		docHeight = LIBRARY.getTotalHeight($JQ('body'));
		SANDG.GENERIC.scrollPage($JQ('body'));
		$JQ('.ajaxOverlay').removeClass('hide').css('height', docHeight + 'px');
		// Greg to fill in here
	},
	
	hideLoading: function(){
		// Greg to fill in here
		$JQ('.ajaxOverlay').addClass('hide');
		SANDG.GENERIC.resizeBoxes();
	}
};

SANDG.PAGINATION = {
	paginationAjaxLinks: function(){
		if(/\/category\/products/.test(window.location.pathname)){
			$JQ('.paginationInner a').unbind('click').bind('click', function() {
				if(this.rel && this.rel!=''){
					var partials=this.rel;
					var query_string=this.href.split('?')[1];
					var href='/'+SANDG.FORMS.getCurrentLanguageFromURL()+'/productsearchajax?'+SANDG.PAGINATION.replaceQueryString(query_string, 'partials', partials);
					SANDG.AJAX.showLoading();
					$JQ('#productListPage').load(href, null, SANDG.AJAX.hideLoading); // #productListPage is specific to products - change for other pagination
					return false;
				}
			});
		}
	},
	
	replaceQueryString: function(url,param,value) {
	    var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
	    if (url.match(re))
	        return url.replace(re,'$1' + param + "=" + value + '$2');
	    else
	        return url + '&' + param + "=" + value;
	}
};

SANDG.FORMS = {
	currentLanguage : "en",	
		
	imposeMaxLength: function() {
		var txts = $JQ('.inputRemaining');
		txts.each(function(i, txtarea){
			
			if(/^[0-9]+$/.test($JQ(this).attr("maxlength"))) 
			{
				$JQ(this).keyup(function(){
					var len = parseInt($JQ(this).attr("maxlength"), 10);
					
					var remaining = len - $JQ(this).val().length;
					
					// update the label
					$JQ(this).parents("div.formRow").find(".charsRemaining").text(remaining);
					
					
					if($JQ(this).val().length > len) {
						alert('Maximum length exceeded: ' + len);
						$JQ(this).val($JQ(this).val().substr(0, len));
						return false;
					}
				});
			}
		});
	
	},
	
	// called from an iframe. bloody messy but works like a charm! :)
	resetMaxLengthCounts : function(formId){
		$JQ('form#'+formId).find(".inputRemaining").each(function(i, txt){
			_maxLength = $JQ(txt).attr('maxlength');
			$JQ(txt).parents("div.formRow").find(".charsRemaining").text(_maxLength);
			
		});
		
	},
	
	resetStarRating : function (){
		$JQ(document).ready(function(){
			$JQ('input[type=radio].star').rating('select','5');
		});
	},

	bindUntickSearchForm: function(){
		$JQ('#refineClear').unbind('click').bind('click', function() {
			window.location.href='/'+SANDG.FORMS.getCurrentLanguageFromURL()+'/category/products?show=all&orderby=date&order=desc';
			return;
/*			var checkBoxes = $JQ('#category-form :checkbox');
			checkBoxes.each(function(){
				this.checked=false;
			});
			SANDG.FORMS.doProductMenuSearch();
			return false;*/
		});
	},
	
	bindTickSearchForm: function(){
		$JQ('#category-form input:checkbox').click(function() {
			$JQ('#category-form').submit();
			$JQ('#productLandingPageContent').hide();
		});
		$JQ('#category-form input.allProductsCheck').unbind('click').bind('click', function() {
			var checked=$JQ(this).is(':checked');
			$JQ(this).val(null);
			$JQ(this).attr('name','ap'); // so it doesn't submit as a category
			$JQ(this).parent().siblings().find('input:checkbox').each(function(){
				$JQ(this).attr('checked', checked);
			});
			$JQ('#category-form').submit();
			$JQ('#productLandingPageContent').hide();
			return false;
		});
		$JQ('#category-form a.allProductsCheck').unbind('click').bind('click', function() {
			var evt=$JQ.Event(this);
			evt.preventDefault();
			var checked=document.getElementById(this.rel).checked;
			document.getElementById(this.rel).click();
			document.getElementById(this.rel).checked=!checked;
			return false;
		});
	},
	
	productMenuSearch: function(){
		$JQ('#category-form').unbind('click').bind('submit', function(){
			$JQ('#productLandingPageContent').hide();
			return SANDG.FORMS.doProductMenuSearch();
		});
	},
	
	doProductMenuSearch: function(search_text, page_number, orderby, order, partials) {
		var query_string=$JQ('#category-form').serialize();
		if(search_text && 'object'!=typeof search_text) query_string+='&search_text='+escape(search_text);
		if(page_number) query_string+='&page='+parseInt(page_number);
//		if(partials) query_string+='&partials='+$JQ.base64Encode(partials.join('|'));
		if(orderby) query_string+='&orderby='+escape(orderby);
		if(order) query_string+='&order='+escape(order);
		if(partials) query_string+='&partials='+escape(partials);
		SANDG.AJAX.showLoading();
		$JQ('#productListPage').load('/'+SANDG.FORMS.getCurrentLanguageFromURL()+'/productsearchajax?'+query_string, null, SANDG.AJAX.hideLoading);
		return false;
	},
	
	getCurrentLanguageFromURL: function(){
		var m=/^\/([a-z]{2})\//.exec(window.location.pathname);
		return m && m[1] ? m[1] : 'en';
	},
	
	clickProductCheckbox: function(theElement) {
		//var evt=$JQ.Event(theElement);
		//evt.preventDefault();
		var the_checkbox=$JQ($JQ(theElement).parents('label').siblings('input')[0]);
		the_checkbox.attr('checked', !the_checkbox.is(':checked'));
		$JQ('#productLandingPageContent').hide();
		SANDG.FORMS.doProductMenuSearch();
		return false;
	}
};

SANDG.FORMS.sendToFriendForm = function(theId){

	var _theId = theId;

	var $form = $JQ("form#sendToFriendForm-"+_theId);

	var _formHandler = $form.find("input#formHandler").val(); 
	
	this.bindEvents = function(){
		
		$form.find("input#emailSubmit"+_theId).click(function(){

			
	
			$JQ.post("/formhandler", {
				'op':'validate',
				'formHandler': _formHandler,
				'data' : $form.serialize()
			}, function(json, status){
				if(json.success == false && json.errors)
				{
					SANDG.GENERIC.processFormErrors(json.errors, $form);
					return false;
				}
				else
				{
					// if ok we post form
					$form.submit();
				} 
				
			}, "json")
		});
	}


	this.bindEvents();
};

SANDG.FORMS.mailingList = function(){

	var $form = $JQ("form#mailingList");

	var _formHandler = $form.find("input#formHandler").val(); 
	
	this.bindEvents = function(){
		
		$form.find("input#subscribe, input#unsubscribe").click(function(){

			// set the value to action of subscribe or unsubscribe
			// THIS IS THE BUTTON THEY CLICK.
			$JQ("#mailingListAction").val($JQ(this).attr('id'));
			
			$JQ.post("/formhandler", {
				'op':'validate',
				'formHandler': _formHandler,
				'data' : $form.serialize()
			}, function(json, status){

				if(json.success == false && json.errors)
				{
					SANDG.GENERIC.processFormErrors(json.errors, $form);
					return false;
				}
				else
				{
					//return false;
					// if ok we post form
					$form.submit();
				} 
				
			}, "json")
		});

	};


	this.bindEvents();
};

// used for submit beauty tip
// used for come clean feedback and comments.
SANDG.FORMS.commentForm = function(theId){
	var _theId = theId;
	var $form =  $JQ("form#addConfessionForm-"+_theId);

	var _formHandler = $form.find("input#formHandler").val(); 
	
	this.bindEvents = function(){


		// validation event
		$form.find("#reviewSubmit").click(function(){

			// reset the form errors
			$form.find("div.errorRow").empty().hide();
			
			var lang = SANDG.FORMS.currentLanguage;
			
			// validate by ajax 
			$JQ.post('/' + lang + '/formhandler', {
				'op' : 'validate',
				'formHandler' : _formHandler,
				'data' : $form.serialize()
			}, function (json, status){
				if(json.success === false && json.errors)
				{
					SANDG.GENERIC.processFormErrors(json.errors, $form);
					return false;
				}
				else
				{
					if(json.success)
					{
						$form.submit();				
					}
				}
			}, "json");
		});
	},
	
	


	// constructor.
	this.bindEvents();
};

/**
 * Product Review and come clean reviews.
 */
SANDG.FORMS.commentReview = function(){

	var $form = $JQ("form#commentReview");

	var _formHandler = $form.find("input#formHandler").val(); 
	
	this.bindEvents = function(){
		
		$form.find("input#reviewSubmit").click(function(){

			$JQ.post("/formhandler", {
				'op':'validate',
				'formHandler': _formHandler,
				'data' : $form.serialize()
			}, function(json, status){

				if(json.success == false && json.errors)
				{
					SANDG.GENERIC.processFormErrors(json.errors, $form);
					return false;
				}
				else
				{
					// if ok we post form
					$form.submit();
				} 
				
			}, "json")
		});

	};


	this.bindEvents();
};
// *******************************************************************************************