/*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('.google_map').googleMap();
		
		$.Body.find("#newsletter_subscribe label").inFieldLabels({
			fadeOpacity: 0.3,
			fadeDuration: 100
		});
		
		//  Other bindings or whatever...
        $.Body.find('a.login_btn').bind('click', function (event) {
            event.preventDefault();
			var current_url = window.location.pathname;
			//alert(current_url);
			
			//alert('login');
            $.Body.modalBuild({
				file: 'login_form',
				redirect_url: current_url
			});
        });
		
		$.Body.find('.multi_images').multiPics();
		
		/*
		$.Body.find('form:not(.ajax)').submit( function() {
			$(this).find('button')
				.css('opacity','0.4')
				.html('Please Wait')
			;
		});
		*/
		
		$.Body.find('form.ajax').ajaxForm();
		
		$.Body.find('div.logged').hover(
			function() {
				$(this).addClass('hovered');
				$.Body.find('#account_dropdown').slideDown(150);
			},
			function() {
				$(this).removeClass('hovered');
				$.Body.find('#account_dropdown').hide();
			}
		);
		
		$.Body.find('input.generate-password').passwordGenerator();
		
		$.Body.find('#mem_logo_hex').bind('keyup', function() {
			var hex_value = $(this).val();
			var preview = $.Body.find('#uploaded_file span');
			
			//var regColorcode = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;

			//if(regColorcode.test(hex_value) == true)
		

				if(hex_value === '') {
					preview.css('background-color', 'transparent');
				}
				else {
					preview.css('background-color', '#' + hex_value);
				}
			//}
			//else {
			//	alert('not hex');
			//}
	
		});
		
		if ($.Body.find('#mem_logo_hex').length) {
			// Ajax File Upload
		    new AjaxUpload('dir_upload',
		        {
		            action: '/incs/actions/file_upload.php',
		            onSubmit: function(file, extension) {

		                $('#uploaded_file span').html('<img src="/img/design/logo_loading.gif" width="43" height="11" id="logo_load" alt="loading" />');
		                $('#dir_logo').addClass('disabled');
		                this.disable();

		            },
		            onComplete: function(file, response) {

		                // if successful
		                if (response.substring(4,0).toLowerCase() == '<img') {
						
							//alert(response);
						
		                    $('#uploaded_file span').html(response);

		                    $('#logo_preview').load( function() {
		                            $(this).fadeIn('medium');
		                        }
		                    );
		                }
		                else {
		                    $('#uploaded_file span').html('<em>logo preview</em>');
		                    alert(response); // shows error message
		                }

		                // Renable button
		                $('#dir_upload').removeClass('disabled');
		                this.enable();
		            }
		        }
		    );
		}
        //$.Body.find('#file_uploader').fileUpload();
		
		$.Body.find('textarea.has_counter').textareaCounter();
		
		$.Body.find('#lucky_guess').bind('click', function(){
			
			event.preventDefault();
			
			var randomHref = $("#directory_list li").rand().find('a').attr('href');

			window.location = randomHref;
			
		});
			

    });


    //	--	Hey buddy I got your custom jQuery plugins right here...
	
	
    $.prototype.textareaCounter = function() {
	    
		return this.each(function () {
			
			var textarea  = $(this);
			var maxChars = textarea.attr('maxlength');
			var numChars = textarea.val().length;
			var charsRemain = maxChars - numChars;

			var counter = $('<p>')
							.addClass('chars_remaining')
							.attr('id','counter_' + textarea.attr('id'))
							.html('<strong>' + charsRemain + '</strong> characters remaining')
							.insertAfter(textarea);

							
			textarea.bind('keyup', function () {
				
				numChars = textarea.val().length;
				charsRemain = maxChars - numChars;
				
				counter.html('<strong>' + charsRemain + '</strong> characters remaining');
			});
					
		});
	}
	
	
	$.prototype.fileUpload = function () {

		return this.each(function () {
			
			var replace = $(this);
			
			var uploader = new qq.FileUploader({
				element: document.getElementById(replace.attr('id')),
				action: '/incs/actions/file_upload.php',
				
				
				onComplete: function(id, fileName, responseJSON){
					
					//alert(responseJSON);
					//console.log(responseJSON);
					//alert(responseJSON);
				},
				
				debug: true
				
	        });
		});
	};

	// Password generator
	$.prototype.passwordGenerator = function () {

		return this.each(function () {
			
			var input = $(this);
			var link = $('<a>').addClass('password-generator').html('Generate Password');
			var length = 8;
			var password = '';
			var i = 0;
			var rn = 0;

			link.bind('click', function() {
				
				password = '';
				i = 0;
				
				input.val('');
				
				while(i < length){
					
					rn = (Math.floor((Math.random() * 100)) % 94) + 33;
					if ((rn >=33) && (rn <=47)) { continue; }
					if ((rn >=58) && (rn <=64)) { continue; }
					if ((rn >=91) && (rn <=96)) { continue; }
					if ((rn >=123) && (rn <=126)) { continue; }

					i++;
					password += String.fromCharCode(rn);
				}
				
				input.val(password);
				
			});
			
			input.after(link);
			
		});
	};
	
	//	Adds a comment to list, if first comment; creates list
    function commentShow(comment) {

        var comments_list = $.Body.find('ol.comments_list');
		
		if (comments_list.length == 0) {
			
			comments_block = $('<div>').addClass('comments').html('<h2><span>1</span> Member Comment &mdash; <a href="#comment_form">Add yours</a></h2><ol class="comments_list clearfix"></ol>')

			$.Body.find('#form_comment').prev('.help').before(comments_block);
			
			comments_list = $.Body.find('ol.comments_list');
		}
		
		$.ajax({
			url: "/incs/actions/new_comment.php?id==" + comment,
			dataType: 'html',
			success: function(data) {
				
				comments_list.append(data);
				comments_list.find('li:last').slideDown(150);
			}
		});

    };
	
	
	//	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;
					
				
				if(errorType === 'both') {
					shortErrors = true;
					longErrors = true;
				} else if (errorType === 'short') {
					shortErrors = true;
				} else if (errorType === 'long') {
					longErrors = true;
				}
				
				if (formObject.parent().find('div.done').length !== 0) {
					formObject.parent().find('div.done').remove();
				}	

				//button.css('opacity','0.4');
				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) {
							
							//alert('errors');
							
							// create error block if required (and not already there)
							if(longErrors) {

								if (formObject.parent().find('#formErrors').length === 0) {

									errorBlock = $('<div>').attr('id','formErrors').addClass('alert error');
									formObject.before(errorBlock);
								}
								else {
									errorBlock = $('#formErrors');
								}
							}

							// 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) {
										
										if(key !== 'global') {
											errorMessages.push(response.errors[key].master);
										}
										else {
											errorMessages.push(response.errors[key]);
										}
									}
								}
    						}

							var errorCount = errorMessages.length;
							if (errorCount > 0) {
								
								var errorList = $('<ul>');

								for(var i=0; i<errorCount; i++) {
									errorList.append('<li>' + errorMessages[i] + '</li>');
								}

								errorBlock.html(errorList);
								
								
							}
							
							//button.css('opacity','1');
    						button.html(buttonHTML);

							return false;
						}

						// success ?
						else if (response.success) {
							
							if (formObject.attr('id') == 'newsletter_subscribe') {
								formObject.after(response.success).fadeOut('slow', function() {
									$(this).remove();
								});
							}
							else {
						
								$.Body.find('.alert.help').remove();

								formObject.after(response.success).remove();

								$.Body.find('#formErrors').remove();
									
								//formObject.before(response.success);
								
								button.css('opacity','1');
	    						button.html(buttonHTML);
							}

							$('#formErrors').remove();
							
						}
						
						// success ?
						else if (response.redirect) {
							
							window.location.replace(response.redirect);
						}
						
						else if (response.commentID) {
							
							//alert(response.commentID);
							commentShow(response.commentID);
							
							formObject.find('textarea').val('').removeClass('error');
							
							button.css('opacity','1');
    						button.html(buttonHTML);

							$('#formErrors').remove();
						}
						
						else {
							alert('error');
						}
						
						return true;
					}
				});

				return false; // don't process form
			});
		});
	};
	
	
	//	Google Maps
    $.prototype.googleMap = function () {

        return this.each(function () {
            var map_wrap, latitude, longitude, title, address, map, point,
                map_html, marker;

            map_wrap = $(this);
			
            latitude  = map_wrap.data('latitude');
            longitude = map_wrap.data('longitude');
            title     = map_wrap.data('title');
            address   = map_wrap.data('address');
				
			var latlng = new google.maps.LatLng(latitude, longitude);
				
			var myOptions = {
				zoom: 10,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
				
            map = new google.maps.Map(map_wrap[0], myOptions);

            map_html = '<div class="map_html">';
            map_html += '<h2>' + title + '</h2>';
            map_html += '<p>' + address + '</p>';
            map_html += '</div>';
				
			var infowindow = new google.maps.InfoWindow({
				content: map_html
			});
				
			marker = new google.maps.Marker({
				position: latlng, 
				map: map, 
				animation: google.maps.Animation.DROP
			});
				
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.open(map,marker);
			});

        });

    };


	// Multipics gallery
	$.prototype.multiPics = function () {
		
		return this.each(function () {
			
			var container	=	$(this);
			var items		=	container.find('ul.multi_thumbs li');
			var thumbs		=	items.find('a');
			var master		=	container.find('div.master_wrap img');
			
			// Thumb Clicks
			thumbs.bind('click', function() {
				
				var thumb	=	$(this);
		        var src		=	thumb.attr('href');
		
				master.hide();
				
				// new <img> probably faster than doing cache[] lookup ??
				var img = document.createElement('img');
				
		        $(img).load(function() {

		            master.attr('src', src).fadeIn(250);
            
		            items.removeClass('active');
		
		            thumb.parent().addClass('active'); // apply class to <li>

		        }).attr('src', src); // odd, but fixes browser bug, can't remember which one
				
				return false;
					
			});
			
			
			// preload larger images
			thumbs.each( function() {
				
				var tmb = $(this);
				
				var fullsize 		=	$(this).attr('href');
				var cache_fullsize	=	document.createElement('img');
			
				$(cache_fullsize).load(function() {
            		
					tmb.animate({opacity: 1}, 250);

		        }).attr('src', fullsize);
			
			    //cache.push(cache_fullsize);
			});
		});
	};

	//  Flippin' sweet modal window for the log in form
    $.prototype.modalBuild = function (settings) {

        var config = {};

        if (settings) {
            config = $.extend({
				file: false,
				query: false,
				window_class: false,
				redirect_url: false
			}, settings);
        }
		
        this.each(function () {
            var modal_overlay   = false,
                modal_window    = false,
                viewport        = $(window),
                viewport_height = parseInt(window.innerHeight ? window.innerHeight : viewport.height(), 10),
                modal_height    = false,
                load_file       = false,
				window_url		= false;

            if (!config.file) {
//              console.log('No file specified');
                return;
            }

			
			window_url = window_url = '/incs/js_tmpl/' + config.file + '.php';
			
			if (config.query) {
				window_url = window_url + '?' + config.query;
			}
			
            load_file = $.ajax({
                dataType: 'html',
                error: function (xhr, textStatus, errorThrown) {
//                  console.log('errorThrown: ' + errorThrown);
                    return;
                },
				data: 'redirect=' + config.redirect_url,
                type: 'GET',
                url: window_url
            });

            load_file.success(function (data, textStatus, xhr) {
                if (!data) {
//                  console.log('No HTML to insert');
                    return;
                }

                $.Head.find('#modal').tmpl([{modal_html: data}]).appendTo($.Body).fadeIn();

                modal_overlay = $.Body.find('#modal_overlay');
				
				
                modal_overlay.height($(document).height()).bind('click', function () {
                    $.Body.modalTeardown();
                });

                modal_window = $.Body.find('#modal_window');
				
				
                // add class to modal window if passed
                if (config.window_class) {
                    modal_window.addClass(config.window_class);
                } else {
                    modal_window.removeClass();
                }
				
				
                modal_window.find('.modal_close').bind('click', function () {
                    $.Body.modalTeardown();
                    return false;
                });

                modal_height = parseInt(modal_window.height(), 10);

                viewport.bind('scrollstop', function () {
                    var scroll_top = viewport.scrollTop(),
                        margin_top = ((viewport_height - modal_height) / 2) + scroll_top;

                    modal_window.animate({marginTop: margin_top}, 250, 'easeOutBack');
                }).trigger('scrollstop');

                $.root.bind('resize', function () {
                    viewport.trigger('scrollstop');
                });

            });
        });

        return this;

    };

    $.prototype.modalTeardown = function () {

        this.each(function () {
            $(this)
                .find('#modal_overlay, #modal_window')
                .animate({opacity: 0}, 250, 'linear', function () {
                    $(this).remove();
                });
        });

        return this;

    };
	

}(jQuery, this, this.document));
//  --  FIX UP; LOOK SHARP!
