$(document).ready(function(){ // WHEN THE DOM IS READY (JUST BEFORE THE PAGE LOADS)...

	//NEWS PAGES
	//moves the month selector to the correct year position on load of the page
	position =  $('.news_years li a#current_year').parent().index() * 27;
	$('#news_mover').attr("style", "top:-"+position+"px;");
	
	//moves the month on click of the years
	$('.news_years li a').click(function(){
		var news_mover = $('#news_mover'),
		position =  $(this).parent().index() * 27;
		news_mover.attr("style", "top:-"+position+"px;");
	})
	$('.acms_news_date_list').last().hide(); // hides the last news nav	
	
	//CALL US TAB
	$('<img />').attr("src", "/images/up_arrow.png");

	$('#call_us_tab').click(function(){
		$('#Call_us_drop_down').toggle()
		var image = $(this).find('img').attr("src"),
			image_up = "/images/up_arrow.png",
			image_down = "/images/down_array.png";
		if (image == image_down){
			$(this).find('img').attr("src", image_up);	
		}else{
			$(this).find('img').attr("src", image_down);
		}
	});

	//CALL BACK FORM			
	$('#callbackForm label, #newsletterForm label').each(function(){
		var labeltext = $(this).text();
		var labelfor = $(this).attr('for');
		$(this).parent().find('#'+labelfor).val(labeltext);
		$(this).hide();
	});
	
	$('#callbackForm input, #callbackForm textarea').click(function(){
		var inputid = $(this).attr('id');
		var labeltext = $(this).parent().find('label[for='+inputid+']').text();
		var inputval = $(this).val();
		if(inputval == labeltext){
			$(this).val('');
		}
	});
	
	$('#callbackForm input, #callbackForm textarea').blur(function(){
		var labeltext = $(this).parent().find('label[for='+inputid+']').text();
		var inputid = $(this).attr('id');		
		var inputval = $(this).val();
		if(inputval == ''){
			$(this).val(labeltext);
		}
	});
	
	
	
	// Handle all enquiry links
	$('a[href*="module/acms_enquiry"]').addClass('car_enquire');
	$('a[href*="module/acms_enquiry"]').addClass('cboxElement');	
		
	// Set height of callback box
	$('.callback_form').css({'height':'28px'})
	
	// Hide inputs
	$('#callbackForm_title').hide();
	$('#callbackForm_name').hide();
	$('#callbackForm_email').hide();
	$('#callbackForm .submit_button').hide();
	$('#callbackForm_time_to_call').hide();
	// Show stuff on number field focus, and make a close button
	$('#callbackForm_phone').focus(function(){
		$('.callback_form').css({'height':'206px'})
		$('#callbackForm_title').show();
		$('#callbackForm_name').show();
		$('#callbackForm_email').show();
		$('#callbackForm .submit_button').show();
		$('#callbackForm_time_to_call').show();

		$('#callbackForm label').show();
		$('#label_callbackForm_phone').hide();
		
		var close_button = $('<a class="callback_close" href="javascript:;"><span>X</span></a>');
		$('#callbackForm').append(close_button);
	});
	
	// Hide form stuff again on blur
	$('a.callback_close').live('click', function(){
		$('.callback_form').css({'height':'26px'})
		$('#callbackForm_phone').val('');
		$('#callbackForm_title').hide();
		$('#callbackForm_name').hide();
		$('#callbackForm_email').hide();
		$('#callbackForm_time_to_call').hide();
		$('#callbackForm .submit_button').hide();
		$('a.callback_close').remove();
		
		$('#callbackForm label').hide();
		form_message('');
	});
	
	var form_is_busy = false;
	
	function form_busy(){
		form_is_busy = true;
		form_message('');
		$('#callbackForm input[type=submit]').css({opacity: 0.5}).val('Sending...');
	}
	
	function form_ready(){
		form_is_busy = false;
		$('#callbackForm input[type=submit]').css({opacity: 1}).val('Call Me Back');
	}
	
	function form_message(message){
		var wrapper = $('.callback_form');
		wrapper.find('.form_message').remove();
		
		var div_message = $('<div></div>');
		div_message.addClass('form_message');
		div_message.html(message);
		
		wrapper.append(div_message);
		
	}
	
	$('#callbackForm').submit(function(e){
					   
		e.preventDefault();
		$('.form_message').removeClass("error");
		$('#callbackForm_phone', '#callbackForm_name', '#callbackForm_email').removeClass("call_back_error");
		var phone = $('#callbackForm_phone').val();
		var title = $('#callbackForm_title').val();
		var name = $('#callbackForm_name').val();
		var email = $('#callbackForm_email').val();
		var time_to_call = $('#callbackForm_time_to_call').val();
		
		saleTrack.addSaleItem(1,0.00,'Call Me Back', email);
		saleTrack.logSale(0);
				   
		var data = {
			formGen_id: 'callbackForm',
			next_step: 2,
			callbackForm_phone: phone,
			callbackForm_title: title,
			callbackForm_name: name,
			callbackForm_email: email,
			callbackForm_time_to_call:time_to_call,
			pageReferrer: 'home'
		}
		
		var url = '/module/acms_callback';
		
		form_busy();
		$.ajax({
			url: url,
			data: data,
			type: 'POST',
			success: function(response_html){
				form_ready();
				
				var context = $(response_html);
				var form_error = 0;
				
				if( $('#callbackForm_phone', context).is('.invalid') ){
					//form_message('Invalid phone number');
					$('#callbackForm_phone').addClass("error");
					form_error = 1;
					console.log('phone');
				}
				
				if( $('#callbackForm_name', context).is('.invalid') ){
					//form_message('Please enter your name');
					$('#callbackForm_name').addClass("error");
					form_error = 1;
					console.log('name');
				}
				
				if( $('#callbackForm_email', context).is('.invalid') ){
					///form_message('Invalid email address');
					$('#callbackForm_email').addClass("error");
					form_error = 1;
					console.log('email');
				}
				
				if(form_error == 1){
					$('.form_message').addClass("error");	
				}else{
					$('.form_message').removeClass("error");
					$('#callbackForm_email, #callbackForm_email, #callbackForm_email').removeClass("error");
				}
				
				var body_text = $('.main_content', context).text();
				if( body_text.match(/Thank you for your enquiry/) ){
					$('#callbackForm input[type=submit]').css('display', 'none');
					$('#callbackForm_email, #callbackForm_email, #callbackForm_email').removeClass("error");
					form_message('Thank you for<br />your enquiry');
						function hide_form(){
							$('.callback_form').css({'height':'26px'})
							$('#callbackForm_phone').val('');
							$('#callbackForm_title').hide();
							$('#callbackForm_name').hide();
							$('#callbackForm_email').hide();
							$('#callbackForm_time_to_call').hide();
							$('#callbackForm .submit_button').hide();
							$('a.callback_close').remove();
							
							$('#callbackForm label').hide();
							form_message('');
						}
					var intervalID = setInterval(hide_form, 1500);
				}
			}
		});
					   
	});
	
	//Image pre-loader for hover states.
	function preload(arrayOfImages) {
    	$(arrayOfImages).each(function(){
        	$('<img/>')[0].src = this;
		});
	}
	
	preload([
    	'/images/green_button_hover.jpg',
    	'/images/button_bg_hover.jpg',
    	'/images/red_button_bg_hover.jpg'
	]);	
	
	// Show and Hide stuff for SEO - this is for copy with links.
	// Drop a button in to open divs
	$("#area_show_hide p").first().append(' <a id="home_more" href="javascript:;">[Read More]</a>');
	$("#area_show_hide p").last().append(' <a id="home_close" href="javascript:;">[Read Less]</a>');
	
	//Hide all but first para on homepage.
	$("#area_show_hide p:not(:first)").hide();
	$("#area_show_hide h3:not(:first)").hide();
	
	// Make buttons work
	$('#home_more').click(function(){
		$("#area_show_hide p:not(:first)").show();
		$("#area_show_hide h3:not(:first)").show();
		$('#home_more').hide();
	});
	
	$('#home_close').click(function(){
		$("#area_show_hide p:not(:first)").hide();
		$("#area_show_hide h3:not(:first)").hide();
		$('#home_more').show();
	});
		
	// Show Hide new cars.
	//truncate('#group_bottom');
	
	$('.readMore').live('click', function() {
		var $hidden = $('.hiddenText');
		if($hidden.is(':hidden')) {
			$hidden.show();
			$(this).insertAfter($('#group_bottom')).children('.readMoreText').text(' [Read Less] ').siblings().hide();
		} else {
			$(this).appendTo($('.revealText')).children('.readMoreText').text(' [Read More] ').siblings().show();
			$hidden.hide();
		}
	});
	
	$('.readMore').click();
	
	/*function truncate(element) {
		$(element + ' p').css({display: 'inline'});
	
		var theText = $(element).html();        // Original Text
		var item;                               // Current tag or text area being iterated
		var convertedText = '<span class="revealText">';    // String that will represent the finished result
		var limit = 150;                        // Max characters (though last word is retained in full)
		var counter = 0;                        // Track how far we've come (compared to limit)
		var lastTag;                            // Hold a reference to the last opening tag
		var lastOpenTags = [];                  // Stores an array of all opening tags (they get removed as tags are closed)
		var nowHiding = false;                  // Flag to set to show that we're now in the hiding phase
	
		if($(element).html() !== null){
			theText = theText.replace(/[\s\n\r]{2,}/g, ' ');            // Consolidate multiple white-space characters down to one. (Otherwise the counter will count each of them.)
			theText = theText.replace(/(<[^<>]+>)/g,'|*|SPLITTER|*|$1|*|SPLITTER|*|');                      // Find all tags, and add a splitter to either side of them.
			theText = theText.replace(/(\|\*\|SPLITTER\|\*\|)(\s*)\|\*\|SPLITTER\|\*\|/g,'$1$2');           // Find consecutive splitters, and replace with one only.
			theText = theText.replace(/^[\s\t\r]*\|\*\|SPLITTER\|\*\||\|\*\|SPLITTER\|\*\|[\s\t\r]*$/g,''); // Get rid of unnecessary splitter (if any) at beginning and end.
			theText = theText.split(/\|\*\|SPLITTER\|\*\|/);            // Split theText where there's a splitter. Now we have an array of tags and words.
		
			for(var i in theText) {                                     // Iterate over the array of tags and words.
				item = theText[i];                                      // Store current iteration in a variable (for convenience)
				lastTag = lastOpenTags[lastOpenTags.length - 1];        // Store last opening tag in a variable (for convenience)
				if( !item.match(/<[^<>]+>/) ) {                         // If 'item' is not a tag, we have text
					if(lastTag && item.charAt(0) == ' ' && !lastTag[1].match(/span|SPAN/)) item = item.substr(1);   // Remove space from beginning of block elements (like IE does) to make results match cross browser
					if(!nowHiding) {                                        // If we haven't started hiding yet...
						counter += item.length;                             // Add length of text to counter.
						if(counter >= limit) {                              // If we're past the limit...
							var length = item.length - 1;                   // Store the current item's length (minus one).
							var position = (length) - (counter - limit);    // Get the position in the text where the limit landed.
							while(position != length) {                     // As long as we haven't reached the end of the text...
								if( !!item.charAt(position).match(/[\s\t\n]/) || position == length )   // Check if we have a space, or are at the end.
									break;                                  // If so, break out of loop.
								else position++;                            // Otherwise, increment position.
							}
							if(position != length) position--;
							var closeTag = '', openTag = '';                // Initialize open and close tag for last tag.
							if(lastTag) {                                   // If there was a last tag,
								closeTag = '</' + lastTag[1] + '>';         // set the close tag to whatever the last tag was,
								openTag = '<' + lastTag[1] + lastTag[2] + '>';  // and the open tag too.
							}
							// Create transition from revealed to hidden with the appropriate tags, and add it to our result string
							var transition = '<span class="readMore"><span class="ellipsis">...</span><span class="readMoreText"> [Read More] </span></span>' + closeTag + '</span><span class="hiddenText">' + openTag;
							convertedText += (position == length)   ? (item).substr(0) + transition
																		: (item).substr(0,position + 1) + transition + (item).substr(position + 1).replace(/^\s/, '&nbsp;');
							nowHiding = true;       // Now we're hiding.
							continue;               // Break out of this iteration.
						}
					}
				} else {                                                // Item wasn't text. It was a tag.
					if(!item.match(/<br>|<BR>/)) {                      // If it is a <br /> tag, ignore it.
						if(!item.match(/\//)) {                         // If it is not a closing tag...
							lastOpenTags.push(item.match(/<(\w+)(\s*[^>]*)>/));     // Store it as the most recent open tag we've found.
						} else {                                                    // If it is a closing tag.
							if(item.match(/<\/(\w+)>/)[1] == lastOpenTags[lastOpenTags.length - 1][1]) {    // If the closing tag is a paired match with the last opening tag...
								lastOpenTags.pop();                                                         // ...remove the last opening tag.
							}
							if(item.match(/<\/[pP]>/)) {            // Check if it is a closing </p> tag
								convertedText += ('<span class="paragraphBreak"><br> <br> </span>');    // If so, add two line breaks to form paragraph
							}
						}
					}
				}   
				convertedText += (item);            // Add the item to the result string.
			}
			convertedText += ('</span>');           // After iterating over all tags and text, close the hiddenText tag.
			$(element).html(convertedText);         // Update the container with the result.
		}
	}*/
	
	
	
})
	

