
/*global jQuery, console, _gaq */

//  This is where the magic happens, like on Cribs, except nowhere near as vile.
(function ($, window, document) {
    //  Is any of this actually going to work?
    if (typeof jQuery === 'undefined') {
        return; // Hot Christ! jQuery isn't available!
    }

    //  --  Instantiate just ONE jQuery object, use this to find other elements
    //      rather than creating a new jQuery object for each selector
    $.root = new $.prototype.init(document);

    //	--	Hey buddy I got your custom jQuery plugins right here...

	$.prototype.elandSearchForm = function () {
		
		this.each(function () {
			var search_input = $(this),
				default_val  = search_input.siblings('legend').text();

			if (!$('.search_form input').val()) {
				search_input.val(default_val);
			}

			search_input
				.bind('focus', function () {
					if ($(this).val() === default_val) {
						$(this).val('');
					}
				})
				.bind('blur', function () {
					if (!$(this).val()) {
						$(this).val(default_val);
					}
				});
		});

		return this;

	};



	$.prototype.globalSlideshow = function () {

        this.each(function () {

            var container          = $(this),
                inner              = container.find('.slider_inner'),
                prev               = container.find('.prev'),
                next               = container.find('.next'),
                list               = container.find('ul'),
                thumbs             = list.find('li'),
                width              = (thumbs.length * thumbs.first().outerWidth(true)),
                max_left           = -width + 454,
                x_pos              = parseInt(0, 10),
                thumb_height       = parseInt(0, 10),
                at_first           = true,
                travelling         = 'right',
                at_last            = false,
                autoStepController = false,
                autoStepExecutor   = false;

            function autoStep() {
                if (travelling === 'right') {
                    if (!at_last) {
                        next.trigger('click', [true]);
                    } else {
                        prev.trigger('click', [true]);
                    }
                } else {
                    if (!at_first) {
                        prev.trigger('click', [true]);
                    } else {
                        next.trigger('click', [true]);
                    }
                }
            }

            function autoStepReset() {
                if (autoStepController) {
                    window.clearTimeout(autoStepController);
                }

                autoStepController = window.setTimeout(function () {
                    autoStepExecutor = window.setInterval(autoStep, 5000);
                }, 5000);

                window.clearInterval(autoStepExecutor);
            }

            (function autoStepInit() {
                autoStepExecutor = window.setInterval(autoStep, 5000);
            }());

            thumbs.each(function () {
                var thumb = $(this);

                if (thumb.innerHeight() > thumb_height) {
                    thumb_height = thumb.innerHeight();
                }
            });

			container.height(thumb_height + 20);
			inner.height(thumb_height + 10);
			thumbs.height(thumb_height - 30);

            list.css('width', width);

            list.find('a').trackLink({
			    event: 'Event',
			    category: 'Product Slideshow',
			    action: 'Click on Product'
		    });

            prev.bind('click', function (event, autoStepper) {
                event.preventDefault();

                if (x_pos === 0) {
                    return;
                }

                travelling = 'left';
                at_last    = false;

                x_pos += 454;

                if (x_pos > 0) {
                    x_pos = 0;
                }

                if (x_pos === 0) {
                    travelling = 'right';
                    at_first   = true;
                }

                if (!autoStepper) {
                    autoStepReset();
                }

                list.stop().animate({left: x_pos}, 250, 'swing');
            });

            next.bind('click', function (event, autoStepper) {
                event.preventDefault();

                if (x_pos === max_left) {
                    return;
                }

                travelling = 'right';
                at_first   = false;

                x_pos -= 454;

                if (x_pos < max_left) {
                    x_pos = max_left;
                }

                if (x_pos === max_left) {
                    travelling = 'left';
                    at_last    = true;
                }

                if (!autoStepper) {
                    autoStepReset();
                }

                list.stop().animate({left: x_pos}, 250, 'swing');
            });

        });

        return this;

    };




    $.prototype.homeSlideshow = function () {

		this.each(function () {
			var container      = $(this),
				list           = $('<ul class="slides"></ul>').appendTo(container),
				slides         = '',
				pager          = $('<ul class="pager" />').insertAfter(list),
				pager_html     = '',
				slides_counter = parseInt(1, 10);

			$.get('/incs/slideshow.csv', function (data) {
				$.each($.csv2json()(data), function () {
					var filename   = $.trim(this.filename),
						url        = $.trim(this.url),
						title      = $.trim(this.title);

					slides += '<li>';

					if (url) {
						slides += '<a href="' + url + '"';

						if (title) {
							slides += ' title="' + title + '"';
						}

						slides += '>';
					}

					slides += '<img alt="' + title + '" src="/img/slides/' + filename + '" />';

					if (url) {
						slides += '</a>';
					}

					slides += '</li>';
				});

				if (slides) {
					$(slides).appendTo(list);

					list.find('a').trackLink({
					    event: 'Event',
					    category: 'Click',
					    action: 'Homepage Slideshow'
				    });

					for (slides_counter; slides_counter <= list.find('li').length; slides_counter += 1) {
						pager_html+= '<li><a href="#">' + slides_counter.toString() + '</a></li>';
					}

					pager.append(pager_html);

					list.cycle({
						activePagerClass: 'active',
						pager: pager,
						pagerAnchorBuilder: function (index) {
							return pager.find('li:eq(' + index + ') a');
						},
						speed: 250,
						timeout: 5000
					});
				}
			});
		});
		
		return this;

	};



    $.prototype.trackLink = function (settings) {

        var config = {
            event:    '',
            category: '',
            action:   '',
            label:    ''
        };
        
        if (settings) {
            $.extend(config, settings);
        }

        this.bind('click', function () {
	        var event    = config.event,
                category = config.category,
                action   = config.action,
                label    = config.label;

			_gaq.push(['_track' + event, category, action, label]);
        });

	    return this;

    };



    //	--	Make Rocket Go Now
    $.root.ready(function () {

        //  Cache the godforsaken <html>, <head> and <body> elements
        $.HTML = $.root.find('html');
        $.Head = $.HTML.find('head');
        $.Body = $.HTML.find('body');

		//  --	Invoke plugins, yo -> body.find('#element').functionName({ ... });
		$.Body.find('.search_form input').elandSearchForm();
		$.Body.find('.cable_slider').globalSlideshow();
		$.Body.find('.slideshow').homeSlideshow();

        $.Body.find('#uk_products > ul').masonry({
            itemSelector: '#uk_products > ul > li'
        });

        $.Body.find('#page a[href^="http://www.eland.co.uk/"]').qtip({
            content: 'En Anglaise',
            position: {
                corner: {
                    target: 'leftMiddle',
                    tooltip: 'rightMiddle'
                }
            },
            style: {
                name: 'blue',
                border: {
                    width: 1,
                    radius: 2
                },
                tip: {
                    corner: 'rightMiddle'
                },
                fontSize: '13px'
            }
        }).trackLink({
            event: 'Event',
            category: 'Outgoing Links',
            action: 'Visit eland.co.uk'
        });

        $.Body.find('#navigation .contact a').trackLink({
		    event: 'Event',
		    category: 'Click',
		    action: 'Contact Page'
	    });

        $.Body.find('.header_details a').bind('click', function () {
            _gaq.push(['_trackPageview', '/email/elandcables.fr']);
        });

        $.Body.find('.contact_form').bind('submit', function () {
            _gaq.push(['_trackEvent', 'Emails', 'Form Submission']);
        });

        $.Body.find('.redirect a').bind('click', function () {
            _gaq.push(['_trackEvent', 'Click', 'Flag', $(this).text()]);
        });

        $.Body.find('#sub_navigation > ul > li a').bind('click', function () {
            _gaq.push(['_trackEvent', 'Click', 'Menu LHS', $(this).data('track')]);
        });

        $.Body.find('.cable_spec_options a').trackLink({
            event: 'Event',
		    category: 'Download',
		    action: 'Spec Sheet'
        });



        //  Other misc bindings
        $.Body.find('table.product_specs tbody tr:even').addClass('even');

		if ($.Body.find('.errors').length) {
			$.Body.find('html').animate({ scrollTop : $.Body.find('.errors').offset().top }, 500);

			$.each([$('.errors'), $('.error')], function () {
				$(this)
					.css({backgroundColor: '#ffdcdc'})
					.animate({backgroundColor: '#fff'}, 1000);
			});
		}

		$.Body.find('#testimonials').cycle({
		    timeout: 10000
	    });
		
	});

}(jQuery, this, this.document));
//  --  FIX UP; LOOK SHARP!

