String.prototype.trim = function() {return $.trim(this)}  // IE Support for trim()
$(document).ready(function() {

	// If #media_photos element exists (Multiple Pages: Media & Front)
	if($('#media_photos').length) {
		//build_photo_thumbs(1);
		build_media_thumbs(1, 'photo'); // Build photos for the 1st page
		change_photo_thumb(0); 			// Set the current photo to the 1st
	}
	
	// If #media_videos element exists (Multiple Pages: Media & Front)
	if($('#media_videos').length) {
		build_video_array(); 
		//build_media_thumbs(1, 'video'); // Build videos for the 1st page
		//change_video_thumb(0); 			// Set the current video to the 1st
	}

	// If #review_page element exists (Customer Reviews Page)
	if($('#review_sources').length) {
		/*$('.review_section a').fancybox({
			width: 900,
			padding: 0,
			margin: 0
		});*/
		$('.review_section .yellow_button').bind('click', show_review_box);
		$('#review_on_northshore').bind('click', review_on_northshore);
	}

	// If #sidebar_contact element exists (All pages with a sidebar)
	if($('#sidebar_contact').length) {
		$('#sidebar_contact_form').bind('submit', sidebar_contact_execute);
		$('#sidebar_response_close').bind('click', sidebar_response_close);
		$('#sbc_dept').bind('change', sidebar_dept_handler);
		sidebar_dept_handler();
		
		// Attach behavior to 'write review' button
		$('#write_review_button').bind('click', show_review_box_all);
		//$('#write_review_button').bind('click', sidebar_write_review_open);
		$('#sidebar_write_review_form').bind('submit', sidebar_write_review_execute);
		$('#sidebar_write_review_close').bind('click', sidebar_write_review_close);
	}
	
	if($('#fp_content').length) {
		$('#fp_carousel').jcarousel({
			auto: 15,
			wrap: 'both',
			scroll: 1,
			initCallback: fpcarousel_init,
			// This tells jCarousel NOT to autobuild prev/next buttons
			buttonNextHTML: null,
			buttonPrevHTML: null,
			// Call methods after each carousel switch
			itemVisibleInCallback: {
			  onBeforeAnimation: fpcarousel_clearcurrent,
			  onAfterAnimation: fpcarousel_setcurrent
			}
		});		
		//$('.jcarousel_element').show();
	}
	
	// Hide "No Javascript" messages (sitewide)
	$('.nojs').hide();
	
	//$('#position_input').selectmenu();
	$('select').selectmenu({style:'dropdown'});
	$('.date_form').datepicker({ changeYear: true });
	// Special Date Rules for 'date of birth' forms
	$('.dob_form').datepicker( "option", "defaultDate", '-30y' );
	$('.dob_form').datepicker( "option", "yearRange", '-60:+20' );
	$('.dob_form').datepicker("refresh");

	// Form Validation Methods
	$('.validate').bind('blur', form_input_validate);
	$('input.validate[type="radio"]').bind('click', form_input_validate);
});

function fpcarousel_init(carousel) {
    $('.jcarousel-control a').bind('click', function() {
        carousel.scroll($.jcarousel.intval($(this).text()));
        return false;
    });
}
function fpcarousel_clearcurrent(carousel, ele, idx) {
	$('.jcarousel-control a').removeClass('carousel_selected');
}
function fpcarousel_setcurrent(carousel, ele, idx) {
	var selector = '.jcarousel-control a:nth-child('+ idx +')';
	$(selector).addClass('carousel_selected');
}



/*
 * Media Center Methods
 * ---------------------
 * build_media_thumbs
 * change_photo_page
 * change_photo_thumb
 * change_video_page
 * change_video_thumb
 * 
 */

/* Function: build_media_thumbs
	Takes the media_array variable (generated by php) and fills the thumbnail portion of the media element

	page: page to display (1st page is 1)
	type: type of thumbnails to generate ('photo' or 'video')
---------------------------------------------*/
function build_media_thumbs(page, type) {
	page = page - 0; // Force Integer
	var output = '';
	var nav_output = '<div id="media_'+type+'_nav" class="media_nav">';
	var is_fp = ($('#fp_content').length) ? true : false;
	
	var page_limit = (is_fp) ? 5 : 9;
	var limit = page_limit * page;
	var prev_page = page - 1;
	var next_page = page + 1;
	var start = 0;
	
	/*if(type == 'video') {
		var yt_url = "http://gdata.youtube.com/feeds/api/users/NorthShoreTowing/uploads?alt=json";
		$.getJSON(yt_url, build_youtube_array)
		console.log(yt_url);
	}*/
	
	// Build the 'previous page' button if needed
	if(page > 1) {
		start = limit - page_limit;
		if(!is_fp) {
			nav_output += '<a href="#" id="'+type+'_prev_nav" class="'+type+'_nav prev_nav" page="'+ prev_page +'">prev</a>';
		}
	}
	
	
	output += '<ul>';
	// Loop through the media array (depending on type and build thumbnail output
	var media_array = (type == 'photo') ? photo_array : video_array;	
	for(var i = start; ((i < media_array.length) && i < limit); i++) {
		var media = media_array[i];
		var thumb = media.thumb;
		if(is_fp && (type == 'photo')) { 
			thumb = media.uri;
		}
		var media_out = '\n<li><a class="'+type+'_thumb" alt="'+ media.title +'" index="'+ i +'" href="'+ media.uri +'">'
						+ '<img src="'+ thumb +'"/></a></li>';
		output += media_out;
	}
	output += '\n</ul>';
							
	
	// Build the 'next page' button if needed
	if(i < media_array.length) {
		if(!is_fp) {
			nav_output += '<a href="#" id="'+type+'_next_nav" class="'+type+'_nav next_nav" page="'+ next_page +'">next</a>';
		}
	}
	// Finish Navigation Output
	nav_output += '</div> <!-- #'+type+'_photo_nav -->';
	
	// Finish building thumbnail output and display
	output += nav_output;
	output += '\n<div class="cb"></div>';
	$('#media_'+type+'_list').html(output);
	
	// Attach methods to generated elements
	if(type == 'photo') {
		$('.photo_nav').bind('click', change_photo_page, false)
		$('.photo_thumb').bind('click', change_photo_thumb, false);
	} else {
		$('.video_nav').bind('click', change_video_page, false)
		$('.video_thumb').bind('click', change_video_thumb, false);	
	}
}

(function($){
$.extend({
    jGFeed : function(url, fnk, num, key){
      // Make sure url to get is defined
      if(url == null) return false;
      // Build Google Feed API URL
      var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
      if(num != null) gurl += "&num="+num;
      if(key != null) gurl += "&key="+key;
      // AJAX request the API
      $.getJSON(gurl, function(data){
        if(typeof fnk == 'function')
		  fnk.call(this, data.responseData.feed);
		else
		  return false;
      });
    }
});
$.extend({
  jYoutube: function( url, size ){
    if(url === null){ return ""; }

    size = (size === null) ? "big" : size;
    var vid;
    var results;

    results = url.match("[\\?&]v=([^&#]*)");

    vid = ( results === null ) ? url : results[1];
	return vid;
/*
    if(size == "small"){
      return "http://img.youtube.com/vi/"+vid+"/2.jpg";
    }else {
      return "http://img.youtube.com/vi/"+vid+"/0.jpg";
    }
	*/
  }
});
})(jQuery);

function build_video_array() {
//http://gdata.youtube.com/feeds/api/users/NorthShoreTowing/uploads?alt=json
	$.jGFeed('http://gdata.youtube.com/feeds/api/users/NorthShoreTowing/uploads',
	function(data) {
		var vid_arr = data.entries;
		for(var idx = 0; idx < vid_arr.length; idx++) {
			var vid = vid_arr[idx];
			var vid_id = $.jYoutube(vid.link);

			var video_uri = 'http://www.youtube.com/v/'+ vid_id+'?f=user_uploads&app=youtube_gdata'
			var video_thumb = 'http://img.youtube.com/vi/'+vid_id +'/0.jpg'
			var video_desc = vid.content; //vid['media$group']['media$description']['$t'];
			var video_title = vid.title; //vid['title']['$t'];
			var video_keys = vid.categories; //vid['media$group']['media$keywords']['$t'];	
			
			video_array[idx] = {
				uri: video_uri,
				desc: video_desc,
				title: video_title,
				thumb: video_thumb
			};
		}
		build_media_thumbs(1, 'video'); // Build videos for the 1st page		
		change_video_thumb(0); 			// Set the current video to the 1st		
	});
}
 
/* Function: change_photo_page
	Changes the thumbnail page of the 'photo' media element
	Calling element (a link) requires the 'page' attribute (target page)
---------------------------------------------*/
function change_photo_page() {
	var target_page = $(this).attr("page");
	build_photo_thumbs(target_page);
	return false;
}

/* Function: change_photo_thumb
	Displays an item from the thumnail page in the 'main photo' section
	
	Calling element (a link) requires the 'index' attribute (target media index)
	manual_index: overrides the attribute-supplied index
---------------------------------------------*/
function change_photo_thumb(manual_index) {
	index = $(this).attr("index");
	if(!index) {
		index = manual_index;
	}
	var photo = photo_array[index];
	
//	var photo_html = '<img src="'+ photoURL.replace(".jpg", "-150x150.jpg") +'"/>';
	var photo_html = '<img src="'+ photo.uri +'"/>';
			photo_html += '<p>'+ photo.desc +'</p>';
	$('#media_photo_main').html(photo_html);	
	$('#photo_title').html(' : '+ photo.title);
	return false;
}

/* Function: change_video_page
	Changes the thumbnail page of the 'video' media element
	Calling element (a link) requires the 'page' attribute (target page)
---------------------------------------------*/
function change_video_page() {
	var target_page = $(this).attr("page");
	build_video_thumbs(target_page);
	return false;
}

/* Function: change_video_thumb
	Displays an item from the thumnail page in the 'main video' section
	
	Calling element (a link) requires the 'index' attribute (target media index)
	manual_index: overrides the attribute-supplied index
---------------------------------------------*/
function change_video_thumb(manual_index) {
	index = $(this).attr("index");
	if(!index) {
		index = manual_index;
	}
	var video = video_array[index];
	
	var width = 300;
	var height = 250;
	var vid_html = '<object width="'+ width +'"  height="'+ height +'">'
								+ '\n<param name="movie" value="'+ video.uri +'"></param>'
								+ '\n<param name="type" value="application/x-shockwave-flash"> '
								+ '\n<param name="allowFullScreen" value="true"></param>'
								+ '\n<param name="allowscriptaccess" value="always"></param>'
								+ '\n<param name="wmode" value="opaque" />'
								+ '\n<embed src='+ video.uri +'allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash"'
								+ ' width="'+ width +'"  height="'+ height +'" wmode="opaque"></embed>\n</object>';
			vid_html += '<p>'+ video.desc +'</p>';
	$('#media_video_main').html(vid_html);	
	$('#video_title').html(' : '+ video.title);
	return false;
}

/*
 * Review Methods
 * ---------------------
 * review_on_northshore
 * show_review_box
 * sidebar_write_review_open
 * sidebar_write_review_execute
 * sidebar_write_review_close
 * 
 */

/* Function: build_media_thumbs
	Hides the lightboxed windows and jumps to the 'write review' section on sidebar
	Page jump handled by link anchor
---------------------------------------------*/
function review_on_northshore() {
	$.fancybox.close();
	sidebar_write_review_open();
}

/* Function: show_review_box
	Displays the 'Write a Review' Lightbox for a review vendor
---------------------------------------------*/
function show_review_box() {
	var target_url = $(this).attr("href");
	var source	   = $(this).attr("source");

	/*
		$GLOBALS['urlGoogle'] = 'http://maps.google.com/maps/place?cid=6346261902799479646&q=North+Shore+Towing,+Evanston,+IL&hl=en&gl=us&view=feature&mcsrc=detailed_reviews&num=100&start=0&ved=0CFcQuAU&sa=X&ei=TADQS8GtEJj-jQPE8_DhDQ';
	$GLOBALS['urlYahoo'] = 'http://local.yahoo.com/info-17275301-north-shore-towing-evanston?tab=reviews&allreviews=1';
	$GLOBALS['urlDexKnows'] = 'http://www.dexknows.com/business_profiles/north_shore_towing-b1290066';
	$GLOBALS['urlYelp'] = 'http://www.yelp.com/biz/north-shore-towing-evanston';
	*/
	
	
	var box = '<div id="review_modal" class="action_box">'
					+ '<h4 class="action_box_head">Write a Review</h4> <!-- .sidebar_box_head -->'
					+ '<p>Please choose from one of the following:</p>'
					+ '<div class="action_center">'
					+ '<a href="'+ target_url +'" id="outside_review_button" class="red_button">Write A Review on '+ source +'</a>'
					+ '</div> <!-- .action_center -->'
					+ '<div class="action_center">'
					+ '<a href="#sidebar_review_jump" id="modal_northshore_review" class="yellow_button">Write A Review on North Shore\'s Website</a>'
					+ '</div> <!-- .action_center -->'
					+ '</div>';
	// Open Fancybox
	$.fancybox(box,	{
			padding: 0,
			margin: 0
		}
	);
	$('#modal_northshore_review').bind('click', review_on_northshore);
	/*$('#outside_review_button').fancybox({  // Fancybox on external not allowed
		width: 900,
		padding: 0,
		margin: 0
	});*/
	return false;
}

function show_review_box_all() {

	var box = '<div id="review_modal" class="action_box">'
					+ '<h4 class="action_box_head">Write a Review</h4> <!-- .sidebar_box_head -->'
					+ '<p>Please choose from one of the following:</p>'
					
		for(var source in review_sources) {
			var review_url = review_sources[source];
			box += '<div class="action_center">'
				+  '<a href="'+ review_url +'" class="outside_review_button red_button">Write A Review on '+ source +'</a>'
				+ '</div> <!-- .action_center -->';
		}					
		box +='<div class="action_center">'
			+ '<a href="#sidebar_review_jump" id="modal_northshore_review" class="yellow_button">Write A Review on North Shore\'s Website</a>'
			+ '</div> <!-- .action_center -->'
			+ '</div> <!-- .action_box #review_modal -->';
			
	// Open Fancybox
	$.fancybox(box,	{
			padding: 0,
			margin: 0
		}
	);
	$('#modal_northshore_review').bind('click', review_on_northshore);
}

/* Function: sidebar_write_review_open
	Slide open the "write a review" form on the sidebar
---------------------------------------------*/
function sidebar_write_review_open() {
	$('#sidebar_review_dyn_response').hide();
	$('#sidebar_write_review').show("fast");
	//return false;
}

/* Function: sidebar_write_review_execute
	Executes the "write a review" form and displays the response
---------------------------------------------*/	
function sidebar_write_review_execute() {
	// Validate Form
	var form_ele = $('#sidebar_write_review_form');
	var	form_invalid = form_submit_validate(form_ele);
	if(form_invalid) {
		//add_form_alert(form_ele, 'Form Contains Errors');
		return false; // Prevent Form Submission
	}
	
	// Get Form Values
	var reviewer = $('#reviewer').val();
	var review_body = $('#review_body').val();

	// Set up AJAX call
	var req_uri = $('#req_uri_review').val();
		req_uri += '?req_type=ajax';
		req_uri += '&reviewer='+ encodeURIComponent(reviewer);
		req_uri += '&review_body='+ encodeURIComponent(review_body);
		
	$.ajax({
		url: req_uri,
		success: function(data) {
			$('#sidebar_review_dyn_response').show('fast');
			$('#sidebar_review_dyn_response').removeClass('response_error response_thanks');
			var resp = jQuery.parseJSON(data);
			if(resp.RESP_CODE == 'ERR') {
				$('#sidebar_review_dyn_response').addClass('response_error');
				var resp_html = '<h4>Error:</h4><ul>';
				for(var i = 0; i < resp.RESPONSE.length; i++) {
					var err = resp.RESPONSE[i];
					resp_html += '<li>'+ err +'</li>';
				}
				resp_html += '<ul>';
				$('#sidebar_review_dyn_response').html(resp_html);
			} else if(resp.RESP_CODE == 'OK') {
				$('#sidebar_review_dyn_response').addClass('response_thanks');
				var resp_html = '<h4>Thanks!</h4><ul>';
					resp_html += 'Your review has been submitted.';
				$('#sidebar_review_dyn_response').html(resp_html);
				
				$('#reviewer').val('');
				$('#review_body').val('');
				hide_form_alert(form_ele);
				
				// Close the 'Thank You' message after 5 seconds
				setTimeout (sidebar_write_review_close, 5000);
			}
		}
	});

	return false; // prevent default form submit		
}

/* Function: sidebar_write_review_close
	Slide closed the "write a review" form on the sidebar
---------------------------------------------*/
function sidebar_write_review_close() {
	$('#sidebar_write_review').hide("fast");	
	return false;
}


/*
 * Sidebar Contact Form Methods
 * ---------------------
 * sidebar_contact_execute
 * sidebar_response_close
 *
 */

/* Function: sidebar_contact_execute
	Executes the "contact us" form on the sidebar and displays the response
---------------------------------------------*/	
function sidebar_contact_execute() {
	// Validate Form
	var form_ele = $('#sidebar_contact_form');
	var	form_invalid = form_submit_validate(form_ele);
	if(form_invalid) {
		//add_form_alert(form_ele, 'Form Contains Errors');
		return false; // Prevent Form Submission
	}
	
	
	
	
	// Get Form Values
	var name = $('#sbc_name').val();
	var email = $('#sbc_email').val();
	var phone = $('#sbc_phone').val();
	var dept = $('#sbc_dept').val();
	var contact_type = $('#contact_type').val();	
	console.log('TEST:'+ dept);
	if(dept == 'auto-parts') {
		var part_year = $('#part_year').val();
		var part_make = $('#part_make').val();
		var part_model = $('#part_model').val();
		var part_type = $('#part_type').val();

		// Set up AJAX call
		var req_uri = $('#req_uri_contact').val();
			req_uri += '?req_type=ajax';
			req_uri += '&name='+ encodeURIComponent(name);
			req_uri += '&email='+ encodeURIComponent(email);
			req_uri += '&phone='+ encodeURIComponent(phone);
			req_uri += '&dept='+ dept;
			req_uri += '&part_year='+ encodeURIComponent(part_year);
			req_uri += '&part_make='+ encodeURIComponent(part_make);
			req_uri += '&part_model='+ encodeURIComponent(part_model);
			req_uri += '&part_type='+ encodeURIComponent(part_type);
			
			req_uri += append_ga_formdata();	
	} else {
		var message = $('#sbc_message').val();

		// Set up AJAX call
		var req_uri = $('#req_uri_contact').val();
			req_uri += '?req_type=ajax';
			req_uri += '&name='+ encodeURIComponent(name);
			req_uri += '&email='+ encodeURIComponent(email);
			req_uri += '&phone='+ encodeURIComponent(phone);
			req_uri += '&dept='+ dept;
			req_uri += '&message='+ encodeURIComponent(message);	
			req_uri += append_ga_formdata();	
	}
	console.log(req_uri);
	
	$.ajax({
		url: req_uri,
		success: function(data) {
			$('#sidebar_contact_response').show('fast');
			$('#sidebar_contact_response').removeClass('response_error response_thanks');
			var resp = jQuery.parseJSON(data);
			if(resp.RESP_CODE == 'ERR') {
				$('#sidebar_contact_response').addClass('response_error');
				var resp_html = '<h4>Error:</h4><ul>';
				for(var i = 0; i < resp.RESPONSE.length; i++) {
					var err = resp.RESPONSE[i];
					resp_html += '<li>'+ err +'</li>';
				}
				resp_html += '<ul>';
				$('#response_message').html(resp_html);
			} else if(resp.RESP_CODE == 'OK') {
				$('#sidebar_contact_response').addClass('response_thanks');
				var resp_html = '<h4>Thanks!</h4><ul>';
					resp_html += 'Your message has been sent.';
					
					// Track this contact conversion on adwords
					resp_html += '<img height=1 width=1 border=0 src=" http://www.googleadservices.com/pagead/conversion/1061044691/imp.gif?value=1&label=signup&script=0">';
				$('#response_message').html(resp_html);
				
				var name = $('#sbc_name').val('');
				var email = $('#sbc_email').val('');
				var phone = $('#sbc_phone').val('');
				var dept = $('#sbc_dept').val();
				if(dept == 'auto-parts') {
					var part_year = $('#part_year').val('');
					var part_make = $('#part_make').val('');
					var part_model = $('#part_model').val('');
					var part_type = $('#part_type').val('');
				} else {
					var message = $('#sbc_message').val('');
				}
				hide_form_alert(form_ele);	
				
				// Track the Virtual Page View
				pageTracker._trackPageview(resp.VPV_RESP);
				
				// Close the 'Thank You' message after 5 seconds
				setTimeout (sidebar_response_close, 5000);
			}
		}
	});

	return false; // prevent default form submit
}

/* Function: sidebar_write_review_close
	Slide closed the "contact us" response on the sidebar
---------------------------------------------*/
function sidebar_response_close() {
	$('#sidebar_contact_response').hide("fast");	
	return false;
}

function sidebar_dept_handler() {
	var dept = $('#sbc_dept').val();
	console.log(dept);
	
	if(dept == 'auto-parts') {
		$('#sidebar_auto_parts_inputs').show();
		$('#sidebar_message_box').hide();
		$('#sbc_message').removeClass('validate required');
		$('#sidebar_auto_parts_inputs input').addClass('validate required');
		$('#sidebar_auto_parts_inputs input').bind('blur', form_input_validate);
	} else {
		$('#sidebar_auto_parts_inputs').hide();
		$('#sidebar_message_box').show();
		$('#sidebar_auto_parts_inputs input').removeClass('validate required');
		$('#sbc_message').addClass('validate required');
		$('#sbc_message').bind('blur', form_input_validate);
	}
}

// sidebar_auto_parts_inputs


/* Function: _uGC
   Code 'borrowed' from urchin.js. Parses a string and returns a value.  
   Used to get data from the __utmz cookie
---------------------------------------------*/
function _uGC(l,n,s) {
 if (!l || l=="" || !n || n=="" || !s || s=="") return "-";
 var i,i2,i3,c="-";
 i=l.indexOf(n);
 i3=n.indexOf("=")+1;
 if (i > -1) {
  i2=l.indexOf(s,i); if (i2 < 0) { i2=l.length; }
  c=l.substring((i+i3),i2);
 }
 return c;
}

/* Function: append_ga_formdata
   Code to get the formdata stored in gA cookies and append it to form requests
---------------------------------------------*/
function append_ga_formdata() {
	// Get the __utmz cookie value. This is the cookies that stores all campaign information. 
	var z = _uGC(document.cookie, '__utmz=', ';');
	z = unescape(z);
	// 
	// The cookie has a number of name-value pairs. 
	// Each identifies an aspect of the campaign. 
	// 
	// utmcsr  = campaign source 
	// utmcmd  = campaign medium 
	// utmctr  = campaign term (keyword) 
	// utmcct  = campaign content  
	// utmccn  = campaign name 
	// utmgclid = unique identifier used when AdWords auto tagging is enabled 
	// 
	// This is very basic code. It separates the campaign-tracking cookie 
	// and populates a variable with each piece of campaign info. 
	// 
	var gasource  = _uGC(z, 'utmcsr=', '|'); 
	var gamedium  = _uGC(z, 'utmcmd=', '|'); 
	var gaterm    = _uGC(z, 'utmctr=', '|'); 
	var gacontent = _uGC(z, 'utmcct=', '|'); 
	var gacampaign = _uGC(z, 'utmccn=', '|'); 
	var gclid   = _uGC(z, 'utmgclid=', '|'); 
	// 
	// The gclid is ONLY present when auto tagging has been enabled. 
	// All other variables, except the term variable, will be '(not set)'. 
	// Because the gclid is only present for Google AdWords we can 
	// populate some other variables that would normally 
	// be left blank. 
	// 
	if (gclid !="-") { 
		  gasource = 'google'; 
		  gamedium = 'cpc'; 
	}  
	//
	// One more bonus piece of information.  
	// We're going to extract the number of visits that the visitor
	// has generated.  It's also stored in a cookie, the __utma cookis
	// 
	var a = _uGC(document.cookie, '__utma=', ';');
	var aParts = a.split(".");
	var gavisits = aParts[5];

	//Set the hidden form fields with GA data
	var ga_formdata = '&gasource='+ gasource
				    + '&gamedium='+ gamedium
				    + '&gaterm='+ gaterm
				    + '&gacontent='+ gacontent
				    + '&gacampaign='+ gacampaign
				    + '&gclid='+ gclid
				    + '&gavisits='+ gavisits;
	return(ga_formdata);
}

function get_ga_formdata() {
	// Get the __utmz cookie value. This is the cookies that stores all campaign information. 
	var z = _uGC(document.cookie, '__utmz=', ';');
	z = unescape(z);
	// 
	// The cookie has a number of name-value pairs. 
	// Each identifies an aspect of the campaign. 
	// 
	// utmcsr  = campaign source 
	// utmcmd  = campaign medium 
	// utmctr  = campaign term (keyword) 
	// utmcct  = campaign content  
	// utmccn  = campaign name 
	// utmgclid = unique identifier used when AdWords auto tagging is enabled 
	// 
	// This is very basic code. It separates the campaign-tracking cookie 
	// and populates a variable with each piece of campaign info. 
	// 
	var gasource  = _uGC(z, 'utmcsr=', '|'); 
	var gamedium  = _uGC(z, 'utmcmd=', '|'); 
	var gaterm    = _uGC(z, 'utmctr=', '|'); 
	var gacontent = _uGC(z, 'utmcct=', '|'); 
	var gacampaign = _uGC(z, 'utmccn=', '|'); 
	var gclid   = _uGC(z, 'utmgclid=', '|'); 
	// 
	// The gclid is ONLY present when auto tagging has been enabled. 
	// All other variables, except the term variable, will be '(not set)'. 
	// Because the gclid is only present for Google AdWords we can 
	// populate some other variables that would normally 
	// be left blank. 
	// 
	if (gclid !="-") { 
		  gasource = 'google'; 
		  gamedium = 'cpc'; 
	}  
	//
	// One more bonus piece of information.  
	// We're going to extract the number of visits that the visitor
	// has generated.  It's also stored in a cookie, the __utma cookis
	// 
	var a = _uGC(document.cookie, '__utma=', ';');
	var aParts = a.split(".");
	var gavisits = aParts[5];
	
	var ga_data = {
		ga_source : gasource,
		ga_medium : gamedium,
		ga_term : gaterm,
		ga_content : gacontent,
		ga_campaign : gacampaign,
		ga_visits : gavisits,
		gclid : gclid		
	};
	return(ga_data);
}


/*
On Focus
	Display any alerts 
On Blur
	Clear 'invalid'
	Clear alerts (from input.id)
	Recheck validation based on classes
	populate alerts
	
	Alerts
	if messages exist, show alertbox (messages hidden)
	
	
Validation
	Check validation
	return false on valid
	return alert message on invalid

*/
function form_input_validate(event, manual_ele) {
	// Get Element from event (no params sent) or from param
	var element = (typeof(manual_ele) != 'undefined') ? manual_ele : $(this);
	
	// Get ID for element
	var ele_id = element.attr('id');
	if(element.attr('type') == 'radio') {
		// Need id to identify alert messages
		ele_id = element.attr('name');
	}
	
	//console.log('valdidate: '+ ele_id);
	// Get alertbox element, create it if it doesn't exist
	var alertbox = element.parent().find('.form_alert');
	if(alertbox.length == 0) {
		element.parent().append('<div class="form_alert"></div>');
		alertbox = element.parent().find('.form_alert');
		alertbox.bind('click',  toggle_validation_alerts);
	}
	
	// If we're validating a replaced selectbox widget, get the actual value
	var select_widget = false;
	if(element.hasClass('ui-selectmenu')) {
		ele_id = ele_id.replace(/-button/gi, "");
		element = $('#'+ ele_id);
		select_widget = true;
	}
	
	// If we're validating a date, we might need to wait for a click on the date selectbox
	// events are 'false' when function is called from the form_submit_validate
	if(element.hasClass('date_form') && !element.hasClass('delay_validation') && event) {
		element.addClass('delay_validation');
		window.setTimeout("$('#"+ele_id+"').blur();", 100);
		return;
	}
	element.removeClass('delay_validation');
	
	// Trim element value and reset
	var value = element.val();
		value = value.trim();
	element.val(value);
	
	// Start Validation
	var is_invalid = false;
	var check_invalid = false;
	remove_validation_alerts(alertbox, ele_id);
	
	/* Validate Required
	------------------------------------*/
	if(element.hasClass('required')) {
		check_invalid = input_validate_required(element);
		if(check_invalid) {
			// Populate Alert
			add_validation_alert(alertbox, ele_id, check_invalid)
			// Set Invalid
			is_invalid = true;
		} else {
			is_invalid = (!is_invalid) ? check_invalid : true;
		}
	}

	/* Validate OrRequired
	------------------------------------*/
	/*
  if(element.hasClass('orrequired')) {
	check_invalid = input_validate_required(element);
	var other_ele_id = element.attr('orreq');
	var other_ele = $('#'+ other_ele_id);
	var other_check_invalid = input_validate_required(other_ele);
	if(check_invalid || other_check_invalid) {
		// Populate Alert
		add_validation_alert(alertbox, ele_id, check_invalid)
	} else {
		is_invalid = (!is_invalid) ? check_invalid : true;
	}
	*/


	/* Validate Email
	------------------------------------*/	
	if(element.hasClass('v_email')) {
		check_invalid = input_validate_email(element);
		if(check_invalid) {
			// Populate Alert
			add_validation_alert(alertbox, ele_id, check_invalid)
			// Set Invalid
			is_invalid = true;
		} else {
			is_invalid = (!is_invalid) ? check_invalid : true;
		}
	}
	
	/* Validate Phone
	------------------------------------*/
	if(element.hasClass('v_phone')) {
		check_invalid = input_validate_phone(element);
		if(check_invalid) {
			// Populate Alert
			add_validation_alert(alertbox, ele_id, check_invalid)
			// Set Invalid
			is_invalid = true;
		} else {
			is_invalid = (!is_invalid) ? check_invalid : true;
		}
	}
	
	/* Validate Zip Code
	------------------------------------*/	
	if(element.hasClass('v_zipcode')) {
		check_invalid = input_validate_zipcode(element);
		if(check_invalid) {
			// Populate Alert
			add_validation_alert(alertbox, ele_id, check_invalid)
			// Set Invalid
			is_invalid = true;
		} else {
			is_invalid = (!is_invalid) ? check_invalid : true;
		}
	}
	
	/* Validate Date
	------------------------------------*/	
	if(element.hasClass('v_date')) {
		check_invalid = input_validate_date(element);
		if(check_invalid) {
			// Populate Alert
			add_validation_alert(alertbox, ele_id, check_invalid)
			// Set Invalid
			is_invalid = true;
		} else {
			is_invalid = (!is_invalid) ? check_invalid : true;
		}
	}	
	
	var ui_element = (select_widget) ? $('#'+ ele_id +'-button') : element;
	
	if(is_invalid) {
		ui_element.addClass('invalid');
		alertbox.show();
		element.one('focus', display_validation_alerts);
		hide_validation_alerts(element);
		return true;
	} else {
		ui_element.removeClass('invalid');
		remove_validation_alerts(alertbox, ele_id)
		return false;
	}
}

function form_submit_validate(form_ele) {
	var v_ele_arr = form_ele.find('.validate');
	
	var form_invalid = false;
	for(var i = 0; i < v_ele_arr.length; i++) {
		var v_ele = $(v_ele_arr[i]);
		var ele_invalid = form_input_validate(false, v_ele);
		form_invalid = (form_invalid == true) ? true : ele_invalid;
	}
	
	return form_invalid;
}

function input_validate_required(element) {

	// Check the type of input
	var type = element.attr('type');
	var name = element.attr('name');
	var value;
	if(type == 'radio') {
		value = $("input[@name='"+name+"']:checked").val();
	} else {
		value = element.val();
	}
	
	if(!value) {
		return 'Required Field Missing';
	} else {
		return false;
	}
}

function input_validate_phone(element) {
	var ele_val = element.val();
	// This is not a check for NULL. If number doesn't exist, return 'valid'
	if(!ele_val) { return false; }
	
	// Remove allowed characters from input
	ele_val = ele_val.replace(/[ -]/gi, "");

	
	// Check for other non-numeric characters
	if(ele_val.match(/\D/gi)) {
		return "Phone Number has invalid characthers";
	}
	
	// Remove Starting '1' from US phone numbers
	if(ele_val.length == 11) {
		ele_val = ele_val.replace(/^1/gi, "");
	}
	
	// Check Phone against valid phone numbers *XX-*XX-XXXX (*: 0 or 1 not allowed)
	if(!ele_val.match(/^[2-9]{1}[0-9]{2}[2-9]{1}[0-9]{2}[0-9]{4}$/gi)) {
		return "Phone Number is not a valid US Number";
	} else {
		return false;
	}
}

function input_validate_zipcode(element) {
	var ele_val = element.val();
	// This is not a check for NULL. If number doesn't exist, return 'valid'
	if(!ele_val) { return false; }
	
	// Check Zipcode against valid phone numbers XXXXX
	if(!ele_val.match(/^[0-9]{5}$/gi)) {
		return "Zipcode is not a valid US zipcode";
	} else {
		return false;
	}
}

function input_validate_email(element) {
	var ele_val = element.val();
	// This is not a check for NULL. If number doesn't exist, return 'valid'
	if(!ele_val) { return false; }
	
	// Check Zipcode against valid phone numbers XXXXX
	if(!ele_val.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/gi)) {
		return "Email is Invalid";
	} else {
		return false;
	}
}

function input_validate_date(element) {
	var ele_val = element.val();
	// This is not a check for NULL. If number doesn't exist, return 'valid'
	if(!ele_val) { return false; }
	
	if(!ele_val.match(/^[0-1][0-9]\/[0-3][0-9]\/[0-9]{4}$/gi)) {
		return "Date Format (MM/DD/YYYY) is invalid";
	}	
	
	var date_arr = ele_val.split('/');
	var month = date_arr[0] - 1;
	var day = date_arr[1];
	var year = date_arr[2];
	
	// If day returned form getDate is not equal to the supplied date, invalid
	var date = new Date(year, month, day);
	if(day != date.getDate()) {
		return "Date is not valid";
	} else {
		return false;
	}
}

function add_form_alert(form_ele, message) {
	var submit = form_ele.find('input[type=submit]');
	var alertbox = submit.parent().find('.form_alert');
	if(alertbox.length == 0) {
		submit.parent().append('<div class="form_alert"></div>');
		alertbox = submit.parent().find('.form_alert');
		alertbox.bind('click',  toggle_validation_alerts);
	}
	add_validation_alert(alertbox, 'form_submit', message);
	alertbox.show();
}

function hide_form_alert(form_ele) {
	var submit = form_ele.find('input[type=submit]');
	var alertbox = submit.parent().find('.form_alert');
	alertbox.hide();
}

function clear_form_alerts(form_ele) {
	var submit = form_ele.find('input[type=submit]');
	var alertbox = submit.parent().find('.form_alert');
	alertbox.find('.alert_mess_box').remove();
	alertbox.hide();	
}

function add_validation_alert(alertbox, ele_id, message) {
	var message_box = alertbox.find('.alert_mess_box');
	if(message_box.length == 0) {
		alertbox.append('<div class="alert_mess_box"></div>');
		message_box = alertbox.find('.alert_mess_box');
	}
	var output = '<div class="alert_item from_'+ele_id+'">'+message+'</div>';
	message_box.append(output);
}

function remove_validation_alerts(alertbox, ele_id) {
	var alert_selector = '.from_'+ ele_id;
	$(alert_selector).remove();
	if(alertbox.find('.alert_mess_box').children().length == 0) {
		alertbox.hide();
	}
	
}

// Called on 'click' on an alertbox
function toggle_validation_alerts() {
	$(this).find('.alert_mess_box').toggle();
}

function display_validation_alerts() {
	var element = $(this);
	if(!element.hasClass('invalid')) { return; }
	// Get message_box element, exit if it doesn't exist.
	var message_box = element.parent().find('.form_alert').find('.alert_mess_box');
	if(message_box.length == 0) {  return; } 
	message_box.show();
}

function hide_validation_alerts(element) {
	// Get message_box element, exit if it doesn't exist.
	var message_box = element.parent().find('.form_alert').find('.alert_mess_box');
	if(message_box.length == 0) {  return; } 
	message_box.hide();
}




