/**
 * @section   : Global JavaScript functions
 * @project   : B-Total
 * @author    : Boye Oomens <boye@e-sites.nl>
 * @version   : 1.0
 */

/* Function to show/log data in the Firebug console */
function log(obj) {
	if (typeof console == 'undefined') return;
	console.log(obj);
}

/* Scrolls to a given element */
jQuery.fn.extend({
	scrollTo : function(speed, easing) {
		if (typeof speed !== 'number') return;
		return this.each(function() {
			var targetOffset = $(this).offset().top - 10;
			$('html, body').animate({scrollTop: targetOffset}, speed, easing);
		});
	}
});

/* Overrides the jQuery getScript method to enable its disabled cache function */
$.getScript = function (url, callback, cache){
	$.ajax({
		type: "GET",
		url: url,
		success: callback,
		dataType: "script",
		cache: cache
	});
};

/* Make getters return full set if first arg === true */
$.each(
    [
        'html', 'val', 'text', 'width', 'height', 'scrollTop',
        'scrollLeft', 'hasClass', 'css', 'attr', 'offset',
        'position', 'outerHeight', 'outerWidth'
    ],
    function(){

        var _method = $.fn[this];

        if (!_method) {
            return true;
        }

        $.fn[this] = function() {

            var args = Array.prototype.slice.call(arguments);

            if (args.shift() === true) {
                return this.map(function(){
                    return _method.apply($(this), args);
                });
            }

            return _method.apply(this, arguments);

        };

    }
);

/* Prevent default semantics */
function noFollow(e) {
	e.preventDefault();
}

/* Shows the title when hovering the box */
function showBoxTitle() {
	var self = this;
	var span = (document.all ? 'SPAN' : 'span');
	if (self.innerHTML.indexOf(span) !== -1) {
		$(self).find('.bg').css('opacity',0.8).end().find('span').show().animate({ bottom:0 }, { queue:false, duration:300 });
	}
}

function hideBoxTitle() {
	var self = this;
	var span = (document.all ? 'SPAN' : 'span');
	if (self.innerHTML.indexOf(span) !== -1) {
		$(self).find('span').animate({ bottom:-22 }, { queue:false, duration:300 });
	}
}

/**
 * Refinement functionality
 * @param none
 */
var handleRefinement = function () {

	/**
	 * Show item
	 * @param {Object} obj
	 * @private
	 */
	function setStatus(active, inactive) {
		hideItems(inactive);
		showItems(active);
	}

	function hideItems(filter) {
		$('#brands a')
			.not('.inactive')
			.filter(filter)
			.find('span')
			.css('opacity', 0.8)
			.hide()
			.fadeIn('fast')
			.end()
			.removeAttr('class')
			.addClass('inactive')
			.unbind()
			.bind('click', noFollow);
	}

	function showItems(filter) {

		filter = (filter === '' ? '.inactive' : filter);

		$('#brands a')
			.not('.active')
			.filter(filter)
			.find('span')
			.fadeTo('fast', 0, function() { $(this).removeAttr('style'); $(this).parent().removeAttr('class'); })
			.end()
			.addClass('active')
			.unbind()
			.hover(showBoxTitle, hideBoxTitle);
	}

	/**
	 * Public methods
	 */
	return {
		init : function () {

			/* Event Delegation */
			$('#refinement .checkbox').bind('click', handleRefinement.setFilter);

			/* Store all related tags in one object */
			var items = $('#brands a'),
				i = $('#brands li:not(.placeholder) a').children().length,
				relatedTags = {};

			/* Iterate over all items (brands/portfolio) */
			while (i--) {
				var name = '#' + items.eq(i).attr('id');
				var value = items.eq(i).attr('rel');

				/* Set default status to active */
				items.eq(i).addClass('active');

				/* Fill relatedTags object */
				relatedTags[name] = value;

				/* Bind object to the #brands element */
				$('#brands').data('relatedTags', relatedTags);
			}

			/* Call setFilter once */
			handleRefinement.setFilter();
		},
		setFilter : function () {
			/* Vars */
			var self = this,
				relatedTags = $('#brands').data('relatedTags'),
				options = $('#refinement').find('input[type=checkbox]:checked').attr(true, 'value').sort(),
				i = options.length,
				activeItems = [],
				inactiveItems = [];

				/* Iterate over all options */
				while (i--) {
					for (id in relatedTags) {
						if (relatedTags.hasOwnProperty(id)) {
							var item = relatedTags[id];
							/* Check if the option matches against the property value and fill the particular array */
							if (item !== '' && typeof item !== 'undefined' && item.indexOf(options[i]) !== -1 && $.inArray(id, activeItems) === -1) {
								activeItems.push(id);
							} else {
								inactiveItems.push(id);
							}
						}
					}
				}

				/* Typecast the arrays to strings since they serve as a selector */
				var active = activeItems.join();
				var inactive = inactiveItems.join();

				/* Show all items if the inactive array is empty */
				if (inactiveItems.length < 1) {
					showItems();
				}

				/* Set status for all items */
				setStatus(active, inactive);

				/* Ajax call for session handling */
				if (typeof this.value !== 'undefined') {
					$.ajax({
						method: 'GET',
						url: '/php/ajaxHandler.php',
						data: 'option=' + this.value + '&status=' + this.checked,
						success: function (data) {
							log(data);
						}
					});
				}
		}
	};
}();

/**
 * Newsletter signup process
 * @author Boye Oomens <boye@e-sites.nl>
 * @param  {Object} e
 */
function newsLetterSignup(e) {
	return $(this).chkFrm(e, {
		scroll: false,
		headMsg: '',
		footMsg: '',
		onSuccess: function () {
			/* Hide error container */
			$(e.target).prevAll('p.error').hide();

			/* Serialize formdata */
			var formData = $(e.target).serializeArray();

			/* Hide several elements and show a preloader */
			$('#newsletter > *').fadeTo('fast', 0, function () {
				$(this).parent('#newsletter').css('background', 'url(/images/misc/ajax-loader.gif) no-repeat center center');
			});

			/* Invoke Ajax call and pass on the serialized data (use a timer to show the interaction) */
			setTimeout(function () {
				$.ajax({
					type: 'POST',
					url: '/php/newsletterSignup.php',
					data: formData,
					success: function (html) {
						/* Append data to the DOM */
						$('#newsletter').removeAttr('style').children().hide().end().append(html).find('.succesfull').fadeIn('fast');
					},
					error: function (response) {
						log(response.responseText);
					}
				});
			}, 1500);

			/* Prevent default semantics */
			e.preventDefault();
		}
	});
}

/**
 * Simple tab function
 * @author: Boye Oomens <boye@e-sites.nl>
 * @required: jQuery (1.3.2)
 * @usage: call initTabs() on DOM ready
 */
var initTabs = function(){

	if ($('#tabContainer:has(div.hideIfJS)').length < 1) return;

	// Expand on page load / If there is an hash, open that tab
	if (window.location.hash && location.href.indexOf("#") !== -1) {
		var sHash = location.href.substr(location.href.indexOf("#") + 1),
			activeTab = sHash;
		$('a[rel='+activeTab+']').parent('li').addClass('active');
	}

	if ($('#tabs li.active').length < 1) {
		$('#tabs li:first-child').addClass('active');
        var activeTab =  $('#tabs li:first-child').find('a').attr('rel');
	} else {
		var activeTab = $('#tabs li.active').find('a').attr('rel');
	}

    $('#'+activeTab).show();

    $('#tabs a').not('.disabled').bind('click', function (e){
		$('#tabs .active').attr('class','');
		$(this).parent('li').addClass('active');
		var currentTab = $(this).attr('rel');
		$('.pane').hide();
		$('#'+currentTab).show();
	});
};

/**
 * Small jQuery extension to trigger a focus event on the first form element
 * @author Boye Oomens <boye@e-sites.nl>
 * @usage $('#formId').focusOnFirstElement('.error');
 * @param {String] exp - expression to filter specific elements
 * @return {Object} this
 */
jQuery.fn.extend({
	focusOnFirstElement : function (exp) {

		var exp = (typeof exp != 'undefined' ? exp : '');

		return this.each(function () {
			var self = this;
			$(self)
				.find('input, textarea, select')
				.not('[type=submit]')
				.filter(exp + ':enabled:first')
				.trigger('focus');
		});
	}
});

/**
 * Small jQuery extension to empty an input field on focus and put the standard value back onblur
 * @author Boye Oomens <boye@e-sites.nl>
 * @usage $('#quickSearch').emptyFieldOnFocus();
 * @return {Object} this
 */
jQuery.fn.extend({
	emptyFieldOnFocus : function () {

		var invalidTypes = ['hidden', 'submit', 'radio', 'checkbox'],
			frm = $(this),
			frmElements = frm.find('input[type=text], textarea'),
			index = frmElements.length;

		return frm.each(function(index) {

			var self = frmElements[index],
				def = self.value;

			/* Check whether if we are dealing with the correct input type */
			for (var i = 0, length = invalidTypes.length; i < length; i++) {
				if (invalidTypes[i] === self.getAttribute('type')) {
					return false;
				}
			}

			/* Set event handlers */
			self.onfocus = function () {
				if (this.value === def) {
					this.value = '';
				} else {
					this.select();
				}
			};
			self.onblur = function () {
				if (this.value === '') {
					this.value = def;
				}
			};

		});
	}
});