// CarZen-specific additions to the jQuery library

jQuery.fn.extend({
  // ==== Description
  // Converts any element ID to its integer representation.
  // 
  // ==== Examples
  //   $('#myfav_32').getID(); // returns 32
  // 
  // ==== Returns
  // <Integer>:: the integer id
  getId: function() {
    return parseInt($(this).attr("id").match(/\d+/)[0]);
  },
  clearDefault: function() {
    if (this.val() == this.attr('defaultValue')) this.val("");
  },
	
	fadeUp: function(speed) {
		$(this).css({'position':'relative'}).animate({top:"-150px", opacity: 0}, speed, function() { $(this).hide(); })
	},
	
	carousel: function(options) {
		var carousel_wrapper = '<div class="carousel-wrapper"></div>';
		var width = options.width ? options.width : $(this).width();
		var height = options.height ? options.height : $(this).parent().height();
		var left = options.left ? options.left : 0;
		var top  = options.top ? options.top : 0;
		var caddy = $(this);
		var pages = options.pages;
		var total_width = pages * width;
		caddy.parent().css({'position' : 'relative'});
		caddy.wrap(carousel_wrapper);
		caddy.css({'white-space': 'nowrap', 'position' : 'absolute', 'top' : '0px', 'left' : '0px', 'width': total_width + 'px', 'height': height + 'px'});
		caddy.parent().css({'width': width + 'px', 'height' : height + 'px', 'position' : 'absolute', 'overflow' : 'hidden', 'top' : top + 'px', 'left': left + 'px' });
		var currentLeft = function() {
			return parseInt(caddy.css('left'));
		}
		var page_left = function() {
			var current = currentLeft();
			var at_page = (current * -1) / width;
			if (at_page == 0) { return false; }
			var future_left = current + width;
			$(caddy).animate({left: future_left});
			return false;
		};
		var page_right = function() {
			var current = currentLeft();
			var at_page = (current * -1) / width;
			if (at_page >= (pages - 1)) { return false; }
			var future_left = current - width;
			$(caddy).animate({left: future_left});
			return false;
		};
		var getPage = function() {
			return currentLeft() / width;
		}
		if (options.prev_page_link) { $(options.prev_page_link).click(page_left); }
		if (options.next_page_link) { $(options.next_page_link).click(page_right); }
	}
});


CarZen = window.CarZen || {};
$.extend(CarZen, {
	flash: {
		initialize: function() {
			$('#flash .flash-close').livequery('click', function() {
				$('#flash').fadeUp('slow');
		  });
		}
	},
	nav: {
		current: false,
		initialize: function() {
			var cz = this;
			$('a.nav-item').each(function() {
				if ($(this).is('.current')) {	
					cz.current = $(this).attr('id'); 
					cz.hover(this);
				}
				$(this).mouseover(function() {
					cz.hover(this);
				});
				$(this).mouseout(function() {
					if (cz.current == $(this).attr('id')) { 
						return; 
					}
					cz.out(this);
				});
			});
		},
		hover: function(el) {
			var img = $(el).children('img:first');
			var current = $(img).attr('src');
			$(img).attr('src', current.replace(/off/,'over'));
		},
		out: function(el) {
			var img = $(el).children('img:first');
			var current = $(img).attr('src');
			$(img).attr('src', current.replace(/over/,'off'));
		}
	},
  favorites: {
		initialize: function() {
			$('#mysearch-div .search-top a').livequery('click', function() {
				CarZen.favorites.show();
		  });
		  $('#myfavorites-div .myfavorites-top a').livequery('click', function() {
		    CarZen.favorites.hide();
		  });
		  $('#myfavorites-div div.close').livequery('click',
		    function(e) {
		      var vehicleId = $(this).parents("div:first").getId();
		      CarZen.favorites.remove(vehicleId);
		    }
		  );
		$('.add-to-favs-link').click(function() {
			CarZen.favorites.add($(this).getId());
		});
		},
		show: function() {
			$('#mysearch-div').hide();
			$('#myfavorites-div').show();
		},
		hide: function() {
			// console.log('hide');
			$('#myfavorites-div').hide();
	    $('#mysearch-div').show();
		},
    add: function(vid) {
      jQuery.post("/favorites/add/" + vid, {}, function(data) {
        CarZen.favorites.load(data.html);
      }, "json");
			CarZen.favorites.show();
    },
    remove: function(vid) {
			$('#myfav_' + vid).fadeUp(1000);
      jQuery.post("/favorites/remove/" + vid, {});
    },
    load: function(html) {
      $('#myfavorites-list').replaceWith(html);
    },
		validateSubmit: function() {
			// should have between 1 and 4 vehicles
			var vehicles = $('form#myfavorites-form :checkbox').fieldValue();
			return (vehicles.length <= 4 && vehicles.length > 0);
		},
		submit: function(action) {
			if (this.validateSubmit()) {
				$('form#myfavorites-form').attr('action', action).submit();
				return true;
			} else {
				this.sendError('You must select between 1 and 4 cars.');
				return false;
			}
		},
		sendError: function(error_msg) {
			$('#myfavorites-list div.inline_error').show().html(error_msg);
		}
  },
  saved_states: {
		initialize: function() {
		  $('#mysearch-list .close a').livequery('click',
		    function(e) {
		      var state_id = $(this).parents("tr:first").getId();
		      CarZen.saved_states.remove(state_id);
		    }
		  );
		},
    add: function(key) {
      $.post("/saved_states/create", {key: key}, function(html) {
        CarZen.saved_states.load(html);
      });
			CarZen.favorites.hide();
    },
    remove: function(id) {
			$('#saved_state_' + id).fadeUp(1000);
      $.ajax({
				type: 'DELETE',
				url: "/saved_states/" + id
			});
    },
    load: function(html) {
      $('#mysearch-list').html(html);
    }
  },
	compare: {
		arrow_closed_src: '/images/compare/green_teal_arrow.gif',
		arrow_open_src: '/images/compare/green_teal_arrow_down.gif',
		initialize: function() {
			var cz = this;
			cz.hideAll();
			$('table.section.expandable td.col_0').click(function() {
				var section_name = $(this).attr('id').replace('compare_section_head_','');
				cz.toggleSection(section_name);
			});
			$('.expand-all').click(function() {
				if ($(this).hasClass('disabled')) { return false; }
	      $(this).addClass('disabled');
	      $(this).siblings('.collapse-all').removeClass('disabled');
				cz.showAll();
				return false;
	    });

	    $('.collapse-all').click(function() {
				if ($(this).hasClass('disabled')) { return false; }
	      $(this).addClass('disabled');
	      $(this).siblings('.expand-all').removeClass('disabled');
				cz.hideAll();
				return false;
	    });
		},
		toggleSection: function(section_name) {
			if ($('#compare_section_details_' + section_name).is(':visible')) {
				this.hideSection(section_name);
			} else {
				this.showSection(section_name);
			}
		},
		showSection: function(section_name) {
			$('#compare_section_details_' + section_name).slideDown();
			var arrow = $('#compare_section_head_' + section_name + ' img.arrow');
			arrow.parent('table').addClass('section-expanded');
			arrow.attr('src', this.arrow_open_src);
		},
		hideSection: function(section_name) {
			$('#compare_section_details_' + section_name).slideUp();
			var arrow = $('#compare_section_head_' + section_name + ' img.arrow');
			arrow.parent('table').removeClass('section-expanded');
			arrow.attr('src', this.arrow_closed_src);
		},
		hideAll: function() {
			var cz = this;
			$('table.section.expandable td.col_0').each(function() {
				var section_name = $(this).attr('id').replace('compare_section_head_','');
				cz.hideSection(section_name);
			});
		},
		showAll: function() {
			var cz = this;
			$('table.section.expandable td.col_0').each(function() {
				var section_name = $(this).attr('id').replace('compare_section_head_','');
				cz.showSection(section_name);
			});
		},
		toggleAll: function() {
			$('table.section.expandable td.col_0').each(function() {
				$(this).trigger('click');
			});
		}
	},
	car_pages: {
		multimedia: {
			slideshow: {
				initialize: function(slideshow_id, num_images, per_page, setPhotoCallback) {
					var cz = this;
					var num_pages = num_images / per_page + (num_images%per_page > 0 ? 1 : 0);
					$('#' + slideshow_id + '_thumbs').carousel({
						top: 0, 
						left: 25, 
						width: 540, 
						height: 80, 
						pages: num_pages, 
						prev_page_link: '#' + slideshow_id + ' .multimedia-scroll-module .scroll-left a', 
						next_page_link: '#' + slideshow_id + ' .multimedia-scroll-module .scroll-right a'
					});
					$('#' + slideshow_id + ' .scroll-thumbs .multimedia-thumb').click(function() {
						var image_id = $(this).getId();
						cz.setPhoto(slideshow_id, image_id, setPhotoCallback);
						return false;
					});
					$('#' + slideshow_id + ' .previous').click(function() {
						cz.setPhoto(slideshow_id, cz.prevId(cz.getCurrentImageId(slideshow_id), num_images), setPhotoCallback);
						return false;
					});
					$('#' + slideshow_id + ' .next').click(function() {
						cz.setPhoto(slideshow_id, cz.nextId(cz.getCurrentImageId(slideshow_id), num_images), setPhotoCallback);
						return false;
					});
				},
				nextId: function(current, num_images) {
					if ((current + 1) >= num_images) {
						return 0;
					} else {
						return current + 1;
					}
				},
				prevId: function(current, num_images) {
						if ((current) == 0) {
							return num_images - 1;
						} else {
							return current - 1;
						}
				},
				setPhoto: function(slideshow_id, image_id, callback) {
					var image = $('#' + slideshow_id + '_main_' + image_id);
					$('#' + slideshow_id + ' .multimedia-main-img img.current').fadeOut(1000, function () { $(this).removeClass('current') });
					image.fadeIn(1000, function() { image.addClass('current');});
					callback($(image));
				},
				setCurrentText: function(slideshow_id, to) {
					$('#' + slideshow_id + ' .multimedia-current-text').html(to);
				},
				getCurrentImageId: function(slideshow_id) {
					return $('#' + slideshow_id + ' .multimedia-main-img img.current').getId();
				}
			}
		}
	},
	car_pages_landing: {
		initialize: function() {
			var cz = this;
			$('span.checkable').each(function() {
				var span  = $(this)
				var checkbox = $(this).children('input[type=checkbox]:first');
				var label		 = $(this).children('label:first');
				checkbox.hide();
				label.attr('for', '');
				if ($(checkbox.fieldValue()).index(checkbox.val()) != -1) {  span.addClass('selected'); }
				span.click(function() {
					if ($(this).is('.selected')) {
						cz.unCheckCheckableOption(this);
					} else {
						cz.checkCheckableOption(this);
					}
					return false;
				});
			});
			$('a.select-all').click(function() {
				$(this).parents('div.filter-group').find('span.checkable, p span.checkable').each(function() {
					cz.checkCheckableOption(this);
				});
				return false;
			});
				$('a.deselect-all').click(function() {
					$(this).parents('div.filter-group').find('span.checkable, p span.checkable').each(function() {
						cz.unCheckCheckableOption(this);
					});
					return false;
				});
		},
		checkCheckableOption: function(span, checkbox) {
			var span  = $(span)
			if (typeof checkbox == 'undefined') {
				var checkbox = span.children('input[type=checkbox]:first');
			}
			span.addClass('selected');	
			checkbox.attr('checked', 'checked');
		},
		unCheckCheckableOption: function(span, checkbox) {
			var span  = $(span)
			if (typeof checkbox == 'undefined') {
				var checkbox = span.children('input[type=checkbox]:first');
			}
			span.removeClass('selected');	
			checkbox.attr('checked', '');
		}
	},
	ask_friend: {
		upload: {
			form_toggle: '.ask-friend-my-photo-link',
			form_div: '.ask-friend-my-photo-form',
			form_form: '#ask-friend-my-photo-form',
			image:	'#ask-friend-my-photo-image',
			errors_div: '.ask-friend-my-photo-errors',
			initialize: function() {
				var cz = this;
				$(cz.form_toggle).click(function() {
					$(cz.form_div).slideToggle();
					return false;
				});
				// $(cz.form_form + ' input[type=file]').filestyle({
				// 	image: '/images/button_browse.gif',
				// 	imagewidth: 81,
				// 	imageheight: 25,
				// 	width: 50
				// });
				this.setupForm();
			},
			setupForm: function() {
				var cz = this;
				$(this.form_form).ajaxForm({
					dataType: 'html',
					success: cz.uploadSuccess,
					url: '/accounts/upload?format=js',
					iframe: true
				});
			},
			uploadSuccess: function(response) {
				var response_html = $(response).select('pre').html() || response;
				eval("var response_json = " + response_html);
				if (typeof response_json.success == 'undefined') {
					// console.log(response);
					CarZen.ask_friend.upload.showErrors(false);
				} else if (response_json.success == true) {
					var img = $('#ask-friend-my-photo-image')
					img.attr("src", response_json.url + "?new");
					$(CarZen.ask_friend.upload.form_div).slideUp();
				} else {
					CarZen.ask_friend.upload.showErrors(response);
				}
			},
			showErrors: function(response) {
				// console.log(response);
				if (response && response.errors) {
					$(this.errors_div).html(response.errors);
				} else {
					
				}
			}
		},
		ratings: {
			initialize: function() {
				$('.vehicle_rating_star').rating({required: true, callback: CarZen.ask_friend.ratings.submit});
			},
			submit: function(value, link) {
				var vehicle_id = $(this.form).getId();
				var url				 = $(this.form).attr("action");
				$.post(url, {
											vehicle_id: vehicle_id, 
											rating: value
										}, 
										function(response) { CarZen.ask_friend.ratings.updateRatings(this, response); },
										'json'
								);
			},
			updateRatings: function(rating_object, response) {
				var just_rated_vehicle = response.rating.vehicle_rating.vehicle_id;
				var cz = CarZen.ask_friend.ratings;
				$('.ask-friend-rating-info').each(function() {
					vehicle_id = $(this).getId();
					$(this).html(cz.ratingText(response.avg_ratings[vehicle_id]));
				});
				cz.replaceStarsForVehicle(just_rated_vehicle, response.avg_ratings[just_rated_vehicle].avg);
			},
			ratingText: function(rating) {
				var text = (rating.num > 1) ? 'Ratings' : 'Rating'
				return rating.num + " " + text;
			},
			replaceStarsForVehicle: function(vehicle_id, new_value) {
				$('#vehicle_rating_for_' + vehicle_id + '_stars').html('');
				for (i=1; i<6; i++) {
					$('#vehicle_rating_for_' + vehicle_id + '_stars').append(this.ratingStar(i, new_value >= i, true));
				}
			},
			ratingStar: function(num, on, readonly) {
				if (typeof on	  == 'undefined') { on 	=	 true };
				if (typeof readonly == 'undefined') { readonly = true };
				var star = $('<div class="star"><a title="' + num + '">' + num + '</a></div>');
				if (readonly) {
					$(star).addClass('star_readonly');
				} else { 
					$(star).addClass('star_live')
				}
				if (on) {
					$(star).addClass('star_on');
				}
				return star;
			}
		}
	}
});

// When the DOM has loaded, add click functionality to the mysearch and myfavorites tabs.
// Also, enable the 'remove' favorites button using livequery, so that new favorites get
// the javascript events connected to them as they are loaded.
$(function() {
	// $("img[@src$=png], div.box-body, div.flash-top-round, div.flash-bottom-round, div.flash-container, div.left-top-round, div.left-bottom-round, div.left-container, div.flash-container div.flash-close").pngfix();
	CarZen.nav.initialize();
	CarZen.favorites.initialize();
	CarZen.saved_states.initialize();
	CarZen.flash.initialize();
});