$(function() {
	
	$('.video').fancybox({
		'titleShow'     : false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack'
	});

	$('.backToTop').click(function() {
		$.scrollTo('html,body', 500);
		return false;
	});
	
	$("#gallery .images li a").click(function() {
		$("#largePreview").html("<img src=\""+$(this).attr('href')+"\" />");
		return false;
	});


	$('textarea').live('click', function() {
		$(this).prettyComments();
	});
	
	$('textarea').prettyComments();
	
	$('section#introduction > nav > ul li a').each(function() {
		var $this = $(this);
		var quote = $('section#introduction > article > blockquote span');
		var otherSpans = $this.parent('li').siblings().children('span');
		$this.hover(function() {
			otherSpans.stop().delay(200).animate({ backgroundColor: "#999"}, 'slow');
			quote.parent().stop().animate({opacity: 0 }, 'fast', function() {
				$(this).removeClass('design print web exhib marketing');
				$(this).addClass($this.attr('rel'));
				quote.html($this.attr('title'));
				$(this).animate({opacity: 1}, 'fast');
			})
		}, function() {
			otherSpans.each(function() {
				$(this).stop().animate({backgroundColor: $(this).attr('rel')}, 'slow');
			});
		});
	});
	
	jQuery.fn.blindToggle = function(speed, easing, callback) {
		var h = this.height() + parseInt(this.css('paddingTop')) + parseInt(this.css('paddingBottom'));
		if(speed == 0) {
			var mt = parseInt(this.css('marginTop')) <0 ? 0 : -h;
			return this.css({'marginTop': mt});
		} else {			
			return this.animate({marginTop: parseInt(this.css('marginTop')) <0 ? 0 : -h}, speed, easing, callback);
		}
	};
	
	function camelize(string) {
        var a = string.split('_'), i;
        s = [];
        for (i=0; i<a.length; i++){
            s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
        }
        s = s.join('');
        return s;
    }
	
	jQuery.easing.def = "easeOutCubic";
	
	$("#tracker").blindToggle(0);
	
	$("a.jobtracker").live('click', function(){
//		$("#tracker").blindToggle("slow", 'easeOutBounce', loadJobs);
		$("#tracker").blindToggle("slow", 'easeOutBounce');
		$(this).toggleClass("active"); 
		return false;
	});

/*
	function loadJobs() {
		var loadPlace = $('#tracker #trackerInner ul#jobs');
		var loadUrl = '/jobs/yourjobs';
		$.get(  
			loadUrl,  
			{ajax: 'true'},  
			function(responseText){
				$('span', loadPlace).fadeOut('slow', function() {					
					$("#tracker #trackerInner ul#jobs").html(responseText);
					
					$('ul#jobs li').hover(function() {
						$('img', this).stop().animate({ marginTop: "-10px" }, 200);
						$('a', this).stop().animate({ bottom: "-10px" }, 200);
					},function(){
						$('img', this).stop().animate({ marginTop: "0px" }, 300);
						$('a', this).stop().animate({ bottom: "5px" }, 200);
					});

					$('ul#jobs li a').click(function(event) {
						event.stopPropagation();		
					}).each(function() {
						var $this = $(this);
						$this.closest('li').click(function() {
							document.location = $this.attr('href');	
							return false;
						});
					});
					
				});
			},  
			"html"  
		);
	}
	$('a.move-left').click(function() {
		var $ul = $('ul#jobs');
		var left = parseInt($ul.css('left'));
		var newLeft = left-130;
		$('ul#jobs').animate({left: newLeft+"px"}, 500, 'easeInBack');
		return false;
	});
	$('a.move-right').click(function() {
		var $ul = $('ul#jobs');
		var left = parseInt($ul.css('left'));
		var newLeft = left+130;
		$('ul#jobs').animate({left: newLeft+"px"}, 500, 'easeInBack');
		return false;
	});
	*/
	
	/*****
	 * Any a which href is linking to the login page will show a modal to login.
	 ****/
	
	function renderLogin() {
		// show login elements
		// fade out any elements not needed
		$('.auth-element').fadeOut('slow');
		// get the jobtracker header
		$.get('/users/jobtracker', false, function(data) {
			$('body').append(data);
			$("#tracker").blindToggle(0);
		});
		// change the login link
		$('#wrapper > header > nav li.last').html('<a href="/jobtracker/logout">Logout</a>');
	}
	
	$('form#ajaxLogin').live('submit', function(e) {
		e.preventDefault();
		$(this).ajaxSubmit({
			dataType: 'json',
			url: '/jobtracker/login.json',
			success: function(data, statusTxt, xhr, $form) {
				if(data.error) {
					createFlash(data.error);
				} else if(data.success == true) {
					$.fancybox.close();
					renderLogin();
					if(data.redirect) {
						window.location = data.redirect;
					} else if(data.flash) {
						createFlash(data.flash);
					} else {
						createFlash('You have logged in');
					}
				} 
			}
		});
	});
	
	function loginForm(orig) {
		$.fancybox({
			'orig'			: $('header#globalHeader li.last a'),
			'padding'		: 0,
			'href'			: '/jobtracker/login?ajax',
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic'
		});
	}
	
	$('a[href="/jobtracker/login"]').live('click', function(event) {
		event.preventDefault();
		loginForm();
	});
	
	/*****
	 * Any element that has a href that links to a job, will show a hover preview before clicking. It will also make the surrounding article clickable to the link of the a.
	 ****/
	$("a[href^='/jobtracker/viewjob/'], a[href^='/designers/jobs/viewjob/']").click(function(event) {
		event.stopPropagation();		
	}).each(function() {
		var $this = $(this);
		$this.closest('article').click(function() {
			document.location = $this.attr('href');	
			return false;
		});
	}).jobPreview();
	
	$('section#yourjobs article').equalHeights();
	
	$('section#proofs figure a').click(function(event) {
		event.stopPropagation();		
	}).each(function() {
		var $this = $(this);
		$this.closest('figure').click(function() {
			document.location = $this.attr('href');	
			return false;
		});
	});
	
	
	$('#ten-commitments section').tabs();

	$('form#bidForm').ajaxForm({
		dataType:  'json',
		url: '/bids/place.json',
		success: function(data, statusText, xhr, $form) {
			if(data.error) {
				createFlash(data.error);								
			} else {
				$form.slideUp();
				if(data.flash) {					
					createFlash(data.flash);
				}
				var $bidsUpdate = $form.parent().find('ul#bids');
				$bidsUpdate.load('/bids/listBids/'+$bidsUpdate.attr('rel'));
			}
		}
	});
	
	
	/*****
	 * If you add a "bubble" class to an <a> - this will look for the nearest <li> which can then be used for clicking too.
	 ****/
	$('a.bubble').click(function(event) {
		event.stopPropagation();		
	}).each(function() {
		var $this = $(this);
		$this.closest('li').click(function() {
			document.location = $this.attr('href');	
			return false;
		});
	});
	
	$('a.art-bubble').click(function(event) {
		event.stopPropagation();		
	}).each(function() {
		var $this = $(this);
		$this.closest('article').click(function() {
			document.location = $this.attr('href');	
			return false;
		});
	});
	
	/*****
	 * Ajax modal box for the no obligation text
	 ****/
	$("a.no-obligation").click(function(e) {
		e.preventDefault();
		return false;
	});
	
	
	
	/*****
	 * Make all of the offers the same height, so that the design looks the same
	 ****/
	function offerHeights() {
		$('.sector-offers > ul > li, .sector-offers > article').equalHeights();		
	}
	offerHeights();
	
		var offers = $('.sector-offers > ul > li');
		/*****
		 * Change opacity of the offer the user is hovering over, creating focus.
		 * This needs checking in IE <<<<<
		 ****/
		offers.hover(
			function() {
				$(this).stop().animate({"opacity": "1"}, "medium");
			},
			function() {
				$(this).stop().animate({"opacity": "0.4"}, "medium");
			}
		);
	
			/*****
			 * Scroll to the appropriate form when a offer is clicked on
			 ****/
			offers.css('cursor', 'pointer');
			offers.click(function() {
				var thisForm = $('form', this);
				$.scrollTo(thisForm, 900);
			});
	
				/*****
				 * Format the currency of the input box on blur.
				 ****/
				$('input[rel=currency]').blur(function() {
					$(this).formatCurrency();
				});
					$('form', offers).ajaxForm({
						dataType:  'json',
						url: '/bids/bidOnOffer.json',
						success: function(data, statusText, xhr, $form) {
							if(data.login_required) {
								createFlash('Please login then re-submit your bid.');
								loginForm();
							} else {
								if(data.error) {
									createFlash(data.error);								
								} else {
									$form.slideUp();
									$form.parent().find('footer').html("<p>GOOD LUCK! We will let you know shortly if your bid is 'fair' enough to proceed.</p>");
								}
							}
						}
					});
					
	
	/*****
	 * Other form shizzle
	 ****/
	$('select.hasOther').live('change', function() {
		var $this = $(this);
		var fieldName = $this.attr('name');
		if($this.val() == "other") {
			// change the label
			var label = $this.parent('div').children('label');
			label.html(label.html()+'<span class="small">Please state</span>');
			// change the field
			var $newField = $(document.createElement('input')).attr('name', fieldName).attr('type', 'text');
			$this.replaceWith($newField);
			$newField.focus();		
		}
	});
	$('#familiar-check').click(function() {
		if($(this).is(':checked')) {
			$('#familiar').fadeIn();
		} else {
			$('#familiar').fadeOut();
		}
	});
	$('select#PrintQuoteProductRequired').change(function() {
		if($(this).val() == "DL Folded Leaflets") {
			$('#PrintQuotePanels').parent().fadeIn();
			$('#PrintQuotePages').parent().fadeOut();
		} else {
			$('#PrintQuotePanels').parent().fadeOut();
			$('#PrintQuotePages').parent().fadeIn();
		}
	});
	$('#PrintQuotePanels').parent().hide();
	
	
	$('#job-request-form').ajaxForm({
		dataType: 'json',
		url: '/quotes/request.json',
		success: function(data, statusTxt, xhr, $form) {
			$('.error-message').remove();
			if(data.login_required) {
				createFlash('Please login then re-submit your job request.');
				loginForm();
			} else {
				if(data.validationErrors) {
					$.each(data.validationErrors, function(model, errors) {
			            for (fieldName in this) {
			                var element = $("#" + camelize(model + '_' + fieldName));
			                var _insert = $(document.createElement('div')).insertAfter(element);
			                _insert.addClass('error-message').text(this[fieldName])
			            }
			        });				
				}
				if(data.error) {
					createFlash(data.error);
				} else if(data.success == true) {
					if(data.redirect) {
						window.location = data.redirect;
					} else if(data.flash) {
						createFlash(data.flash);
					}
				}
			}	
		}
	});
	
	/*****
	 * File Upload System
	 ****/
	$('article.upload').equalHeights();
	
	
	/*****
	 * Proofing System.
	This will need to have the option to delete annotations.
	But not after save is clicked
	Maximum character limit?
	
	
	 ****/
	function getFormField(id) {
		return '<a class="button">Show Comment</a><span><textarea name="data[ProofComment]['+id+'][comment]"></textarea> <a href="#" class="cancel">Cancel</a>  <a href="#" class="save">Save</a></span>';
	}
	
	function showExistingComment(annotation){
	  return $(document.createElement('span')).addClass('proofComment saved').html('<a class="button">Show Comment</a><span><blockquote>'+annotation.ProofComment.comment+'</blockquote> <a href="#" class="delete">Delete</a></span>').attr('rel', annotation.ProofComment.id);
	}
	
	function showExistingCommentDesigner(annotation){
	  return $(document.createElement('span')).addClass('proofComment saved').html('<a class="button">Show Comment</a><span><blockquote>'+annotation.ProofComment.comment+'</blockquote></span>').attr('rel', annotation.ProofComment.id);
	}

	if($('#image-wrapper').length) {
		
		if (typeof designer == 'undefined') {
			// mage the image commentable
			$('#image-wrapper').annotatableImage(function(id){
				return $(document.createElement('span')).addClass('proofComment toSave').html(getFormField(id));
			}, {xPosition: 'left'});
		}

		// debug, when clicked ; prints ul with list of clicked events
		$('#serialize').click(function(event){
			event.preventDefault();
			$.each($('#image-wrapper span.toSave').seralizeAnnotations(), function(){
				$('#serializedOutput ul').append($(document.createElement('li')).html('<strong>x:</strong> ' + this.x + ' <strong>y:</strong> ' + this.y));
			});

		});
		
		$('.proofComment.toSave a.cancel').live('click', function(e) {
			e.preventDefault();
			// remove the comment
			$(this).parent().parent('.toSave').fadeOut('fast', function() {
				$(this).remove();
			});
		});

		// if there are existing comments add them to the image
		if (typeof proofImageId != 'undefined') {
			// get the comments in json form
			$.getJSON('/proof_comments/getComments/'+proofImageId+'.json', function(data) {
				if(!data.length) { $('.hide-comments').fadeOut(); }
				// when loaded, hide the loading element
				$('#image-wrapper p.loading').fadeOut('slow', function() {
					// when the loading element is hidden add the comments
					if (typeof designer == 'undefined') {
						$('#image-wrapper').addAnnotations(showExistingComment, data);
					} else {
						$('#image-wrapper').addAnnotations(showExistingCommentDesigner, data);						
					}
				});
			});
			
			$('.proofComment.toSave a.save').live('click', function(e) {
				e.preventDefault();
				// set up the variable for the commentData
				var commentData = [];

				// the actual comment in the dom
				var $comment = $(this).parent().parent('.proofComment');
				// the comments text
				var commentText = $('textarea', $comment).val();
				
				// searialize the annotations
				$.each($comment.seralizeAnnotations(), function() {
					// put the data in the commentData variable
					commentData = {x: this.x, y: this.y, comment: commentText, proof_image_id: proofImageId};
				});
				
				// fire an ajax request to send the comment data
				$.ajax({
					url: '/proof_comments/save.json',
					type: 'POST',
					dataType: 'json',
					data: commentData,
					success: function(data) {
						// if there was an error
						if(data.error) {
							// tell the user
							createFlash(data.error);
						} else if(data.success) {
							// remove the comment
							$comment.remove();
							// if the comment that was just added has been returned
							if(data.added_comment) {
								// add the comment
								$('#image-wrapper').addAnnotations(showExistingComment, data.added_comment);
								$('.hide-comments').fadeIn();
							}
							// tell the user it was saved
							createFlash('Your comment was saved!');
						} else {
							// tell them something went wrong
							createFlash('Soething went wrong');
						}
					}
				});
			});
			
			// chekc if they really want to delete
			// maybe need a cancle delete button
			$('.proofComment.saved a.delete').live('click', function(e) {
				$(this).html('Yes, I\'m sure').removeClass('delete').addClass('sure-delete');
			});
			
			// they are sure they want to delete the comment
			$('.proofComment.saved a.sure-delete').live('click', function(e) {
				e.preventDefault();
				
				// the actual comment in the dom
				var $comment = $(this).parent().parent('.proofComment');
				
				// fire an ajax request to send the comment id, ask to delete
				$.ajax({
					url: '/proof_comments/delete.json',
					dataType: 'json',
					type: 'POST',
					data: {id: $comment.attr('rel')},
					success: function(data) {
						if(data.error) {
							// something went wrong, tell them
							createFlash(data.error);
						} else if(data.success) {
							// remove the comment from the page
							$comment.fadeOut('fast', function() {
								$(this).remove();
							});
							// tell the user
							createFlash('Your comment was deleted!');
						} else {
							createFlash('Soething went wrong');
						}
					}
				});
				
			});
			
			$('.proofComment.saved > a.button').live('click', function(e) {
				$(this).siblings('span').toggleClass('visible');
			});
			
		}
		
		// the existing comments fade in and fade out functions
		// the existing comments fade in and fade out functions
				$('span.proofComment.saved').live('mouseover mouseout', function(e) {
					if(e.type == 'mouseover') {
					//	$('span', this).fadeIn('fast');
						$(this).css('z-index', '99');
					} else {
					//	$('span', this).fadeOut('fast');
						$(this).css('z-index', '50');
					}
				});

		
			// when a textarea is focused, bring it to the front
			$('span.proofComment span textarea').live('focus', function(e) {
				var parentSpan = $(this).parent('span').parent('span');
				parentSpan.css('z-index', '98');
				$(this).prettyComments();
			});
		
			// when blured send to back
			$('span.proofComment span textarea').live('blur', function(e) {
				var parentSpan = $(this).parent('span').parent('span');
				parentSpan.css('z-index', '50');
			});
		
		
		
		
		
		// change the color of the proofComments by changeing classes
		$('ul.color-changer li').click(function() {
			var $this = $(this);
			var color = $this.attr('rel');
			$('span.proofComment a.button').removeClass('orange blue red green black white'); // faggy way
			$('span.proofComment a.button').addClass(color);
		});
		
		$('a.hide-comments').live('click', function(e) {
			$('span.proofComment').hide();
			$(this).html('Show Comments').removeClass('hide-comments').addClass('show-comments');
			return false;
		});
		
		$('a.show-comments').live('click', function(e) {
			$('span.proofComment').show();
			$(this).html('Hide Comments').removeClass('show-comments').addClass('hide-comments');
			return false;
		});
	}
	
	/*****
	 * Flashes.
	 ****/

	function flashMessage(obj) {
		obj.addClass('flash');

		var w = obj.width();
		var ow = obj.outerWidth();	
		var ml = (w + (ow - w)) / 2;	

		obj.css("margin-left", "-" + ml + "px");
		obj.css("left", "50%");
		var alerttimer = window.setTimeout(function () {
			obj.trigger('click');
		}, 5000);
		
		obj.animate({opacity: '1', bottom: '140px'}, 300).click(function () {
			window.clearTimeout(alerttimer);
			obj.animate({opacity: '0', 'bottom': '130px'}, 200, 'easeOutCubic', function() {
				obj.remove();
			});
			
		});
	}

	var flash = $('#flashMessage');
		
	if(flash.length) {
		flashMessage(flash);
	}
	
	function createFlash(str) {
		var rand = Math.floor(Math.random()*11);
		var flashelement = "flashMessage"+rand;
		$('body').append('<div id="'+flashelement+'"></div>');
		$('#'+flashelement).html(str);
		$('.flash').fadeOut('fast');
		flashMessage($('#'+flashelement));
	}
});
