/*jslint evil: false, strict: false, undef: true, white: false, onevar:false, browser:true, plusplus:false */
/*global jQuery,window, Cufon:true */

(function($, app){

	var initTypography = function(){
		// Dealer logo
		Cufon.replace('.dealer-logo a', {fontFamily: 'Volkswagen'});

		// Main header
		Cufon.replace('#page-title div.content span', {fontFamily: 'Volkswagen'});

		// Main menu items
		Cufon.replace('#mainmenu a', {fontFamily: 'Volkswagen', hover: true});

		// Content headers
		Cufon.replace('#content h1', {fontFamily: 'Volkswagen'});

		// Used car
		Cufon.replace('div.used-car h2', {fontFamily: 'Volkswagen'});
	};
        

	/**
	*	Init contacts
	*/
	var initContacts = function(){
		equalizeHeights($('.contact .entry'));
	}
	
	/**
	*	Init lightbox
	*/
	var initLightbox = function(){
		$('a[rel*=lightbox]').lightBox();
	}
        
	/**
	* 	Equalize heights
	*                
	*		@param { jQuery Object }		columns			An object containing all the elements 
	*		@param { Number}				colsPrRow		Number of columns in a row
	*
	*/
	var equalizeHeights = function(columns, selector){

		var currentTallest = 0,
		currentRowStart = 0,
		currentDiv,
		rowDivs = [],
		$el,
		topPosition = 0,
		cssSelector = "";
		
		// use default height selector if not set
		cssSelector = selector || "height";
		
		$(columns).each(function() {

			$el = $(this);
			topPosition = $el.position().top;

			if (currentRowStart != topPosition) {

			// we just came to a new row.  Set all the heights on the completed row
			for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
				rowDivs[currentDiv].css(cssSelector, currentTallest);
			}

			// set the variables for the new row
			rowDivs.length = 0; // empty the array
			currentRowStart = topPosition;
			currentTallest = $el.height();
			rowDivs.push($el);

			} else {
				// another div on the current row. Add it to the list and check if it's taller
				rowDivs.push($el);
				currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
			}

			// do the last row
			for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {
				// add last class if needed
				rowDivs[currentDiv].css(cssSelector, currentTallest);
			}
		});
	};



	/**
	*	Product list
	*		- Equalizing the min-height of the columns.
	*/
	var initProductList = function(){  
		
		$(".product-list .entry:nth-child(4)").each(function(){
		      $(this).addClass("last");
		});
		
		equalizeHeights($('.product-list .entry'));
	};
        
        
	/**
	*	Departments
	*		- Equalizing the min-height of the columns.
	*		- Setting onclick handler for the .toogle-opening-hours link.
	*/
	var initDepartments = function(){                
		// hide opening hours
		$('.opening-hours', '.departments').hide();

		equalizeHeights($('.entry'), "min-height");
		equalizeHeights($('.entry h3'));

		// show/hide functionality for opening hours
		$('.toggle-opening-hours:not(.open)').click(function(e){
			$(this).closest('.entry').find('.opening-hours').slideToggle();
			$(e.target).toggleClass("open");
		});
	};


	/**
	*	Service booking
	*/
	var initServiceBooking = function(){
		// hide containers
		$('.book-service .fields, #tblDelivery').hide();
		
		// check the status of the checkboxes
		$('.confirm input:checked').closest('.section').find('.fields').show();

		// set checkboxes click handler
		$('.book-service .cb-delivery').click(function(){
			$('#tblDelivery').slideToggle();
		});
		
		$('.confirm input').click(function(e){
			$(this).closest('.section').find('.fields').slideToggle();
			
			// copy contact information to pickup address.
			if($(this).closest('.pickup-service')){
				var fromAddress = '#ctl00_PHContent_txtAddress';
				var fromZip = '#ctl00_PHContent_txtZipcode';
		    	var fromCity = '#ctl00_PHContent_txtCity';
		    	var toAddress = '#ctl00_PHContent_txtAddress2';
				var toZip = '#ctl00_PHContent_txtZipcode2';
		    	var toCity = '#ctl00_PHContent_txtCity2';
				$(toAddress).val($(fromAddress).val());
				$(toZip).val($(fromZip).val());
				$(toCity).val($(fromCity).val());
			}
		});
	};


	/**
	*	Used cars list
	*		- initialize table sorting and sort by second row by default.
	*		- mark table rows with odd/even classes.
	*
	*/
	var initUsedCarsList = function(){

		$(document).ready( function(){
			$("table.used-cars").tablesorter({
				sortList:[[1,0]],
				widgets: ['zebra']
			});
		});
	};
	
	
	/**
	*	Car valuation
	*/
	var initCarValuation = function(){

		$("#radioDamage input").change(function(){
			if ($(this).val() == 0)
				$("#radioDamage select").attr("disabled", true);
			if ($(this).val() == 1)
				$("#radioDamage select").attr("disabled", false);
		});
	};


	/**
	*	Prepare Links
	*/
	var prepareLinks = function(){

		// find all popup links
		var popupLinks = $('a[rel*=popup]');

		popupLinks.each(
			function(index, link){
				var options = link.rel.split("|");
				var topOffset = Math.round( ( $(window).height() - options[3] ) / 2 );
				var leftOffset = Math.round( ( $(window).width() - options[2] ) / 2 );

				link.onclick = function() {
					var sOptions = "width=" + options[2] + ",height="+ options[3] + ",top=" + topOffset + ",left=" + leftOffset;
					if ( options[4] && options[4] == "scrollbars" ) {
						sOptions += ",scrollbars=yes";
					}
					window.open( link.href, options[1], sOptions  );
				return false;
				};
			}
		);

		// external links and PDF
		$('a[rel=external], a[rel=pdf]').click(function(){
			this.target = "_blank";
		});
	};
        
        
	/**
	*	Init frontpage        
	*/
	var initFrontpage = function(){
		// equalize used-cars containers
		equalizeHeights($('.used-cars .column .content'));

		// equalize used-cars headers
		equalizeHeights($('.used-cars .column .model'));
	};


	// once the dom is ready, start initializing stuff
	$(document).ready( function(){
		initTypography();
		initLightbox();
		prepareLinks();
		
		// frontpage
		if ( $('.frontpage .used-cars').length > 0 )
			initFrontpage();
			
		// departments
		if ( $('.departments').length > 0 )
			initDepartments();
			
		// products
		if ( $('.product-list').length > 0 )
			initProductList();

		// service booking
		if ( $('.book-service').length > 0 )
			initServiceBooking();
			
		// car valuation
		if ( $('.car-valuation').length > 0 )
			initCarValuation();
			
		// contact
		if ( $('.contact').length > 0 )
			initContacts();
			
		// used cars list
		if ( $('table.used-cars').length > 0)
			initUsedCarsList();
			
			
	});
        
}( jQuery, window.IFHA ));

