/*global jQuery */

//  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);

    //	--	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('form.ajax').ajaxForm();
		
		$.Body.find('form.comment label').inFieldLabels({
			fadeOpacity: 0.3,
			fadeDuration: 100
		});
		
		
		$.Body.find('.slideshow').slides({
        	preload: true,
        	preloadImage: '/img/design/loading.gif',
        	play: 5000,
        	pause: 2500,
        	hoverPause: true,
        	generatePagination: false,
        	generateNextPrev: true
        });
		
    });



    //	--	Hey buddy I got your custom jQuery plugins right here...


    //  General video embedder thinger
    $.prototype.videoEmbed = function () {

        this.each(function () {
            var video  = $(this),
                config = {};

            video.empty();

            config.params = {
                allowfullscreen:    true,
                allowscriptaccess: 'always',
                wmode:             'transparent'
            };

            config.swf       = video.data('swf');
            config.height    = video.data('height');
            config.width     = video.data('width');
            config.wmode     = 'transparent';
            config.flashvars = {};

            $.each(video.data('vars'), function (key, value) {
                config.flashvars[key] = value;
            });

            video.flash(config);
        });

		return this;

    };
	

	//AJAX Form Class Integration
	$.prototype.ajaxForm = function () {

		return this.each(function () {

			$(this).submit(function() {

				var	formObject		= $(this),
					button			= formObject.find('button'),
					buttonHTML		= button.html(),
					errorMessages	= [],
					errorBlock		= false,
					shortErrors		= false,
					longErrors		= false,
					errorType		= formObject.data('errortype'),
					key				= false,
					errorsExist		= false;
					
				
				if(errorType === 'both') {
					shortErrors = true;
					longErrors = true;
				} else if (errorType === 'short') {
					shortErrors = true;
				} else if (errorType === 'long') {
					longErrors = true;
				}		


				button.html('Please Wait');

				$.ajax({
					type:		"POST",
					url:		formObject.attr('action'),
					data:		formObject.serialize(),
					dataType:	'json',
					success:	function(response) {

						// Are there errors?
						if (response.errors) {
							
							// create error block if required (and not already there)
							if(longErrors) {

								if (formObject.parent().find('#formErrors').length === 0) {
									
									// not inserting block here, as empty element cause IE8 to choke
									errorBlock = $('<div>')
													.attr('id','formErrors')
													.addClass('alert error');
				
								}
								else {
									errorBlock = $('#formErrors');
									errorsExist = true; // don't insert block later
								}
							}

							// Loop errors
							for (key in response.errors) {
								
								if (response.errors.hasOwnProperty(key)) {
									
									// global errors are not tied to particular field
									if(key !== 'global') {
										
										var input = $('#' + key);
										
										if (shortErrors) {
											
											var shortError;

		         								if (input.parent().find('label strong.short_error').length == 0) {
             
												shortError = $('<strong>').addClass('short_error');
												input.parent().find('label').append(shortError);

		         								}
											else {
												shortError = input.parent().find('label strong.short_error');
											}

											shortError.html(response.errors[key].field);
										}

										input.addClass('error');
									}

									if(longErrors) {

										errorMessages.push(response.errors[key].master);
									}
								}
    						}

							var errorCount = errorMessages.length;
							//alert(errorCount);
							if (errorCount > 0) {

								var errorList = $('<ul />');

								for(var i=0; i<errorCount; i++) {
									errorList.append('<li>' + errorMessages[i] + '</li>');
								}
								
								
								errorBlock.html(errorList);
								
								
								if (!errorsExist) {
									errorBlock.insertBefore(formObject);
								}
							}

    						button.html(buttonHTML);

							return false;
						}

						// success ?
						else if (response.success) {
							
							formObject.after(response.success).remove();

							$('#formErrors').remove();
						}
					}
					/*
					,
					error: function(xhr, textStatus, errorThrown){
		                alert("Error: " +errorThrown)
		            }
					*/
				});

				return false; // don't process form
			});
		});
	};

}(jQuery, this, this.document));
//  --  FIX UP; LOOK SHARP!
