/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	var	resizeImage = function($image, $parent, $container) {
		// Determine the width of the image along with borders and padding
		var imageWidth = $image.width();
		var paddingLeft = parseInt($image.css('padding-left').replace('px', ''), 10);
		var paddingRight = parseInt($image.css('padding-right').replace('px', ''), 10);
		var borderLeft = parseInt($image.css('border-left-width').replace('px', ''), 10);
		var borderRight = parseInt($image.css('border-right-width').replace('px', ''), 10);

		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
		var totalWidth = imageWidth + edgeWidth;

		// Determine parent width
		var parentWidth = $parent.width();

		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;

			$image.width(revisedImageWidth);
			$container.width(parseInt(revisedWidth, 10));
		} else {
			$container.width(totalWidth);
		};
	};

	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be 
		// in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;

		// Find image within div
		var $image = $('img', $(this));
		var $parent = $(this).parent();
		var $container = $(this);

		$image.each(function(index) {
			resizeImage($image, $parent, $container);
			$(this).load(function() {			
				resizeImage($image, $parent, $container);
			});
		});
	});		
};

/**
 * Builds pull quote divs assuming you've wrappted your content with a span with the class: pullquote-left or pullquote-right
 */
$.fn.pullQuote = function() {
	return this.each(function() {
		var contents = $.trim($(this).html());
		var firstCharacterCode = contents.charCodeAt(0);
		if (firstCharacterCode < 65 || firstCharacterCode > 96) {
			contents = '&hellip; ' + contents;
		};
		
		var lastCharacter = contents.charAt(contents.length - 1);
		if ("?!.".search(lastCharacter) < 0) {
			contents = contents + ' &hellip;';
		};
		var $parent = $(this).parent();
		var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
		$parent.before($pullquote);
	});		
};

/**
 * Clears a text form element when it has the style 'clear-default'
 */
$.fn.clickClear = function() {
	return this.each(function() {
		this.defaultValue = $(this).val();
		$(this).click(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).focus(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val(this.defaultValue);
			};
		});
		
		$('form').submit(function(event) {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		});
	});	
};

var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
	};
	
	var	tablePrep = function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	};
	
	listPrep();
	tablePrep();
};

// Loads in Modernizr script which checks for CSS3 capabilities
$('body').ready(function() {
	$.getScript('/js/modernizr.min.js');
});

$(document).ready(function() {
	$('input.clear-default').clickClear();
	$('div.image-left, div.image-right').imageWidth();
	$('span.pullquote-left, span.pullquote-right').pullQuote();
	markupPrep();
	
	// Custom code for NewCity mobile site
	feature_listener();
	pop_up_form_listener();
	form_submit();
	check_for_flash(); // check for flash and replace with image 
	
});

function check_for_flash() {
	// check for flash and replace with image 
		if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]){
		   //...write out the following <EMBED> tag into the document.
		   $('div.mobile-flash').html('<object width="726" height="416"><param name="movie" value="nc_mobileflash.swf"><param name="wmode" value="transparent"><param name="quaility" value="high"><embed src="/flash/nc_mobileflash.swf" width="726" height="416" wmode="transparent" quality="high"></embed></object>');
		}
		else {
		   //...write out the following <IMG> tag into the document. The image need
		   //not be the same size as the Flash Player movie, but it may help you lay out the
		   //page if you can predict the size of the object reliably.
		    $('div.mobile-flash').html('<IMG SRC="/images/nc_mobile_main_flat.jpg" WIDTH="726" HEIGHT="416" ALT="Featured Phones">');
		}

}

function feature_listener () {

	$('#mobile-features .feature-menu li a').hover(
		function () {
			// Remove the arrow form each li a
			$('#mobile-features .feature-menu li a').parent().find('a').removeClass('arrow');
			// Add arrow class to the hovered li a
			$(this).addClass('arrow');
			var element_class = $(this).parent().attr('class');
			element_class = element_class.replace('last', '')
	
			$('#mobile-features .feature-description').find('li').removeClass('active');
			$('#mobile-features .feature-description .'+element_class).addClass('active');
			pageTracker._trackPageview("mobile-promo/feature-"+element_class);
		}
	);
}

function pop_up_form_listener() {
	$("div.sign-up a").click(function () {
	pageTracker._trackPageview("mobile-promo/signup-form");
	$.floatbox({
	        content: 
	        		'<div class="header"><h2>Sign up!</h2><p>We&rsquo;ll contact you about creating a mobile version of your website.</p></div><div class="form-wrapper"><form action="save.php" method="post"><table><tr><th><label for="site" name="site">Your Site Address: </label></th><td><input type="text" name="site" id="web" /></td></tr><tr><th><label for="name" name="name">Your Name: </label></th><td><input type="name" name="name" id="name" /></td></tr><tr><th><label for="email" name="email">Your Email: </label></th><td><input type="email" name="email" id="email" /></td></tr><tr><th><label for="phone" name="phone">Your Phone: </label></th><td><input type="phone" name="phone" id="phone" /></td></tr></table></form><div class="form-buttons"><a class="submit-button"><img src="../images/submit.png" /></a></div></div>',
	        fade: true,
	        boxConfig: {
	        			width: "466px",
	        			height: "325px",
	        			top: "50%",
	        			left: "55%"
		       		 }
	    });
	   // $("#floatbox-box").attr('style', 'height: 325px; width: 466px; top: 50%; left: 50%, background-color: transparent;');
	    form_submit();
	});
	
}

function form_submit () {
	
	$(".form-buttons .submit-button").click(function() {
			var web = $("input#web").val();
			var name = $("input#name").val();
			var email = $("input#email").val();
			var phone = $("input#phone").val();
		  var dataString = 'url='+ web +'&name='+ name + '&email=' + email + '&phone=' + phone;
		  $.ajax({
			    type: "POST",
			    url: "save.php",
			    data: dataString,
			    success: function($data) {
			    	if($data == 1) {
			    		 pageTracker._trackPageview("mobile-promo/signup-thankyou");
			    		 $("#floatbox-box").attr('style', 'height: auto;');
					     $("#floatbox-box .form-wrapper").slideToggle("slow", function(){
					     		 $("#floatbox-box").html('<div class="header"><h2>Thanks!  We will be in touch.</h2><p>We received your information and will be in touch very soon to discuss your mobile site.</p></div><p><a class="close-floatbox" href="/" role="button">Close</a></p>');	
					     });
			    	}
			    	else {
			    		var error = '<p class="error">The form has not been submitted.  Please fill out all of the fields.</p>';
			    		$('.header .error').remove();
			    		$('.header').fadeIn(function() {
					        $('.header').append(error);
					    });
			    	}
			    }
			});
		  return false;
		});

	
}