﻿/* Carbaze.v3 JavaScript */
(function($){
	$.fn.extend({
		// Centers elements to their parents (vertically and horizontally)
		centerToParent: function(){
			$(this).each(function(index, el){
				var elw = $(el).width();
				var elpw = $(el).parent().width();				
				var diff_h = (elw > elpw) ? (elw - elpw) * -1 : (elpw - elw);
				
				var elh = $(el).height();
				var elph = $(el).parent().height();				
				var diff_v = (elh > elph) ? (elh - elph) * -1 : (elph - elh);
				
				$(el).parent().css('textAlign', 'left');
				
				return $(el).css('marginLeft', Math.round(diff_h / 2))
					.css('marginTop', Math.round(diff_v / 2));
			});
		},
		addFbLike: function(url) {
			return $(this).each(function(index, el) {
				$(el).html('<fb:like href="' + url + '" layout="box_count" send="false" width="85" action="recommend"></fb:like>');
			});
		},
		showLoad: function() {
			return $(this).each(function(index, el) {
				var height = $(el).height(),
					width = $(el).width(),
					position = $(el).css('position'),
					loader = $('<div class="loader">Loading...</div>')
						.css('height', height)
						.css('width', width);
						
				$(el).data('originalPosition', position)
					.css('position','relative')
					.append(loader);
				loader.show();
			});
		},
		hideLoad: function() {
			return $(this).each(function(index, el) {
				$(el).find('.loader').hide().remove();
				$(el).css('position', $(el).data('originalPosition'));
			});
		}
	});
})(jQuery);

$(document).ready(function(event){
	
	var History = window.History;

	// No iFrames
	if (window.top !== window.self)
	{
		window.top.location.href = window.self.location.href;
	}
	
	$('img.ctp').load(function(){
		$(this).centerToParent();
	});
	
	//$('.ad, #recommend').show();

	// Init Google +1
	//gapi.plusone.render("plusone", {"size": "tall", "count": "true"});
	
	$('html').css({display:'block'});
	
	//$('input[placeholder],textarea[placeholder]').placeholder();
	$('input#quick_q').placeholder();
	
	$('span.advert').each(function(index, el) {
		$(el).replaceWith('<a href="' + $(el).data('href') + '" target="_blank" title="' + $(el).data('title') + '">' + $(el).html() + '</a>');
	});
	
	/**
	 * Search form JS
	 * @todo	This should be rewritten to be more OO
	 */
	if ($('#search').length) {

		// Set fixed CSS rules to dropdowns
		$('#spacer_manufacturer .dropdown').css('width', $('#spacer_manufacturer').width());
		$('#spacer_details .dropdown').css('width', $('#spacer_details').outerWidth() + $('#spacer_order').width());
		$('#spacer_order .dropdown').css('width', $('#spacer_order').width());

		// Bind closeAll handler to the form
		$('#search').bind('closeAll', function(e) {
			$(this).find('.spacer').trigger('closeDrop');
		}).submit(function(e) {
			e.preventDefault();
			updateResults();
		});

		// Bind closeDrop and showDrop handlers to each form spacer
		$('#search .spacer').bind('closeDrop', function(e) {

			$(this).removeClass('selected').find('.arrow').removeClass('up').addClass('down');
			$(this).find('ul').hide();
			
		}).bind('showDrop', function(e) {

			$(this).addClass('selected').find('.arrow').addClass('up').removeClass('down');
			$(this).find('ul').show();
			
		}).find('a.dodrop').click(function(e) {

			// Decide whether or not the clicked link should show or hide
			if ($(this).parent().hasClass('selected')) {
				$(this).trigger('closeDrop');
			} else {
				$('#search').trigger('closeAll');
				$(this).trigger('showDrop');
			}
		});

		// Style change events
		$('#pick_brand li a').click(function(e) {
			if ($(this).data('id')) {
				e.preventDefault();
				$('#pick_brand li a').removeClass('selected');
				$('#search').trigger('closeAll')
					.find('#brand_id').val($(this).addClass('selected').data('id')).trigger('change');
			}
		});
		$('#pick_order li a').click(function(e) {
			e.preventDefault();
			$('#pick_order li a').removeClass('selected');
			$('#search').trigger('closeAll')
				.find('#order_by').val($(this).addClass('selected').data('id')).trigger('change');
		});

		// Method which serialized the form and updates results (pushing to state)
		var updateResults = function(event, page){
		
			event.preventDefault();
			
			page = page || $('#page').val();
			
			$('#results').showLoad();
			var url = '/' + page;
			
			// Remove the page param from serialized array
			var raw_params = $('#search').serializeArray();
			var params = new Array();
			
			// Remove the page param from serialized array
			$.each(raw_params, function(key, o) {
				if (o.name != 'page') params.push(o);
			});
			
			History.pushState(null, null, url + '?' + $.param(params));
		}
		
		// Events which trigger search
		$('#pick_brand input[type="checkbox"]').change(updateResults);
		$('#brand_id, #order_by, #name, #year-from, #year-to').change(updateResults);
		$('#paginated_results .pagination a').live('click', function(e) {
			updateResults(e, $(this).data('page'));
		});		
		
		$(window).bind('statechange', function(e) {
		
			var State = History.getState(),
				url = State.url,
				rootUrl = History.getRootUrl(),
				relativeUrl = url.replace(rootUrl, '');
			
			$.ajax({
				url: url,
				success: function(data, textStatus, jqXHR) {
					$('#paginated_results').html(data);
					$('#results').hideLoad();
			
					// Inform Google Analytics of the change
					if (typeof window.pageTracker !== 'undefined') {
						window.pageTracker._trackPageview(relativeUrl);
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					document.location.href = url;
					return false;
				}
			});
		});
	}
	
	// Car start
	if ($('#car_profile').length) {
		
		/*
		$('ul.main_menu a').click(function(e){
			var a = $(this);
			$('ul.main_menu li').removeClass('selected');
			a.parent().addClass('selected');
			History.pushState({el_id: a.attr('id')}, a.attr('title'), a.attr('href'));
			e.preventDefault();
		});
		
		$(window).bind('statechange', function() {
			
			var State = History.getState(),
				url = State.url,
				rootUrl = History.getRootUrl(),
				relativeUrl = url.replace(rootUrl, '')
				cont = $('#container .container');
			
			cont.showLoad();
			
			$('ul.main_menu li').removeClass('selected');
			$('#' + State.data.el_id).parent().addClass('selected');

			$.ajax({
				url: url,
				success: function(data, textStatus, jqXHR) {
					cont.html(data).hideLoad();
			
					// Inform Google Analytics of the change
					if (typeof window.pageTracker !== 'undefined') {
						window.pageTracker._trackPageview(relativeUrl);
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					document.location.href = url;
					return false;
				}
			});
		});
		*/
	}
	// Car end
	
});
