// Helper functions
function prepPlaceholder(el) {
	if(el.attr('value') == '' || el.attr('value') == el.attr('placeholdertext')) {
		el.addClass('placeholder');
		if(el.attr('value') == '') {
			el.attr('value', el.attr('placeholdertext'));
		}
	} else {
		el.removeClass('placeholder');
	}
}
function togglePlaceholder(el) {
	// Check if the input already has a value...
	if((el.attr('value') != '') && (el.attr('value') != el.attr('placeholdertext'))) { return false; }
	if(el.attr('value') == el.attr('placeholdertext')) {
		el.attr('value', '');
	} else if(el.attr('value' == '')) {
		el.attr('value', el.attr('placeholdertext'))
	}
	el.toggleClass('placeholder');
}
function clearPlaceholdersOnSubmit() {
	jQuery('form').submit(function(){
		jQuery('input[placeholdertext]').each(function(){
			var _this = jQuery(this);
			if(_this.attr('value') == _this.attr('placeholdertext')) {
				_this.attr('value','');
			}
		});
	});
}
function labelPlaceholders() {
	var els = jQuery('label[for].placeholder');
	els.hide();
	els.each(function(){
		var _this = jQuery(this);
		var _thisfor = '#' + _this.attr('for');
		_thisfor = jQuery(_thisfor);
		_thisfor.attr('placeholdertext',_this.text());
		prepPlaceholder(_thisfor);
		_thisfor.focus(function(){
			togglePlaceholder(_thisfor);
		});
		_thisfor.blur(function(){
			togglePlaceholder(_thisfor);
		});
	});
	clearPlaceholdersOnSubmit();
}

// being set in cf-digg-vote.js.php
/******************************************************
* NOTE: The ui.accordian.js file has been altered
* to meet the requirements of the leaderboard page.
* Alterations: 
*	Lines 63 - 64 have been commented out.
* 		The span that was being appended was breaking 
*		the whole layout of the leaderboard.
******************************************************/
function setLeaderboardAccordian() {
	_accordion = jQuery('#cf-leaderboard tbody');
	
	/* Remove the accordion so we can add it back afresh */
	_accordion.accordion('destroy');
	
	// Leaderboard Accordion
	_accordion.accordion({
		header: 'tr.rankings-slot',
		autoHeight: false,
		animated: false,
		clearStyle:true,
		change: function(event, ui) {
			ui.newContent.find('.rankings-panel .rankings-panel-inside').hide().fadeIn('medium');
		}
	});
}

// Form validation helpers
/* function to trim whitespace from beginning and end of string */

function trimString(str) { 
	return str.replace(/^\s+|\s+$/g, '');
};

/* function to strip non-numeric characters from a string */

function stripAlphaChars(str) {  
	return str.replace(/[^0-9]/g, '');  
}

/* function to strip special characters from a string */
var r={'special':/[\W]/g}
function stripSpecial(o,w) {
  o.value = o.value.replace(r[w],'');
}

/* function to test if string is empty */
function isEmpty(str) {
	str = trimString(str);	
	if(str == null || str == "" || str.length < 2)
		return true;
	return false;
};

/* function to test if string doesn't contain nums*/ 
function isAlpha(str) {
	var pattern = /(^[A-Za-z]+$)/;
	if(pattern.test(str))
		return true;
	return false;
};
	
/* function to test validity of phone number field */

function isValidPhone(p_phone){

	p_phone = stripAlphaChars(p_phone);

	var valid = true;
	
	// we are allowing the format 12345 or 12345-6789
	if ( p_phone == null || p_phone == "" || p_phone.length < 10 || p_phone.length > 10 || isNaN(parseInt(p_phone,10))) {
		valid = false;
	}
	
	for ( var i = 0; i < p_phone.length; i++ ){	
	
		if (isNaN(p_phone.charAt(i)))
			return false;
		}
	
	return valid;
}

/* function to test validity of zip code field */

function isValidZipCode(p_zip) {

	p_zip = stripAlphaChars(p_zip);

	var valid = true;
	
	// we are allowing the format 12345 or 12345-6789
	if (p_zip == null || p_zip == "" || p_zip.length < 5 || p_zip.length > 10 || isNaN(parseInt(p_zip,10)))
		valid = false;
	else if( p_zip.length > 5 && p_zip.charAt(5) != "-" )
		valid = false;
	else if( p_zip.length > 5 && p_zip.charAt(5) == "-" && p_zip.length != 10 )
		valid = false;
	
	for(var i=0;i<p_zip.length;i++) {	
		if(isNaN(p_zip.charAt(i)))
			return false;
	}
	
	return valid;
}

/* function to test validity of email address */

function  isValidEmail(p_email) {
    p_email = trimString( p_email );
    emailpat = /^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
    if( !emailpat.test( p_email ) )
    return false;
    return true;
}
	
/* function to compare email to verify email fields */

function verifyEmail(p_email, p_emailVerify){
	if( p_email.toLowerCase == p_emailVerify.toLowerCase )
		return true;
	return false;
}

function isUrl(s) {
    //need to modify regexp 
	var regexp = /[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
	if( !regexp.test( s ) )
	return false;
	return true;
}




// DOM Ready
jQuery(function($){
	
	// Do placeholders
	labelPlaceholders();
	
	// Slash lists
	if ($.browser.msie) {
		$('.slash li:not(:last-child)').append('/ ');
	} else {
		$('.slash li:not(:last-child)').append(' / ');
	}
	
	// :first-child fix for rule lists
	$('.rule li:first-child').addClass('first-child');
	
	if($.browser.msie) { // Hover fixes
		$('.rankings tr, .rankings th:not("disabled")').hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				$(this).removeClass('hover');
			}
		);
	}
	
	// :hover classname
	/*$('#cf-leaderboard tr td.comments').hover(
		function(){
			$(this).addClass('comments-hover');
		},
		function() {
			$(this).removeClass('comments-hover');
		});*/

	// Sidebar widget Accordion
	$('#tdi-accordion').accordion({
		header: 'h2',
		autoHeight: false,
		clearStyle: true,
		event: 'mouseover'
	});
	
	$('a.video-src').click(function() {
		var embed_src = jQuery(this).attr('href');
		// this is the only way i know to clear the element; let me know if there is a better way
		$('div.gallery-current').html('');
		$('div.gallery-current').flash({
				src: embed_src,
				width: 311,
				height: 241
		});
		$('div.gallery-current div.alt').remove(); // this line has to be here (NEVER DELETE!!)

		return false;
	});
	
	
	/*ARCHIVES*/
	$('.archiveLinksYearHeader').click(function(e){
		e.preventDefault();
		var yearClass = '.a-'+$(this).text();
		if($(this).hasClass('archive-open')){
			$('.widget').find(yearClass).hide();
			$(this).removeClass('archive-open');
		}else{
			$('.widget').find(yearClass).show();
			$(this).addClass('archive-open');
		}
	});
	
	
	/* ZEN PHOTO */
	$('#zenphoto .album').hover(function(){
		$(this).addClass('hover');
	},function(){
		$(this).removeClass('hover');
	});
	
	
	
	// Quick click handler for TDI Tank Wars widget to make table rows anchorable
	$('#rankings-small tr').click(function() {
		location.href = $('#leaderboard-url-for-rankings-small').attr('href');
	});
	
	// Do Appropriate things to the leaderboard guinness record
	var guinness_record = $('#cf-leaderboard tbody tr.guinness-record');
	remove_buttons_for_guinness_row(guinness_record);
	stop_accordian_click_event_for_guinness_row(guinness_record);
	
	// $("#upload-from-computer").click(function(){
	// 	hidden_form_html = '\
	// 		<form name="hidden-picture-uploader" id="hidden-picture-uploader" class="lofi2222">\
	// 			<input id="hidden-picture-file" type="file" name="photo[]" />\
	// 		</form>';
	// 	jQuery(this).parent().append(hidden_form_html);
	// 	jQuery("#hidden-picture-file").change(function(){
	// 		alert(jQuery("#hidden-picture-file").value);
	// 	});
	// 	
	// 	return false;
	// });
	
	// bind to handraiser form
	
$.fn.validatehand = function(options) { 

		// build main options before element iteration 
		var opts = $.extend({}, $.fn.validatehand.defaults, options); 

		// iterate and reformat each matched element 
		return this.each(function() { 
			$this = $(this); 
			// build element specific options 
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
			var IDHash = "#"+$this.attr('id'); 

			//functionality

			$(o.submitId).click(function(){
				
				var valid = true;
				var error = "";
				var field;
				var fieldVal;

				//$("#Warning").remove();
				//$('div#handRaiserContainer div#confirm').hide();
				$("."+o.alertClass).removeClass(o.alertClass);
				
				$("."+ o.requiredClass + " .text").each(function(){
					fieldVal = $(this).val();
					
					if (isEmpty(fieldVal)){
						$(this).parent().addClass(o.alertClass);
						valid = false;
						error = error==""?"*Please fix the fields in red.":error;
					}
					
				});
				
				$("#first_name").each(function(){
					field_value = $(this).val();
					if(field_value){
						if(!isAlpha(field_value)) {
							$(this).parent().addClass(o.alertClass);
							valid = false;
							error = "*Please fix the fields in red.";
						}
					}	
				});
				
				$("#last_name").each(function(){
					field_value = $(this).val();
					if(field_value){
						if(!isAlpha(field_value)) {
							$(this).parent().addClass(o.alertClass);
							valid = false;
							error = "*Please fix the fields in red.";
						}
					}	
				});
				
				$(".zipcode").each(function(){
					field = $(this).find("input");
					if(field.val()){
						if(!isValidZipCode($(field).val())){
							$(this).addClass(o.alertClass);
							valid = false;
							error = "*Zip code must have 5 digits";
						}
					}
				});
				$(".mobile").each(function(){
					field = $(this).find("input");
					if(field.val()){
						if(!isValidPhone($(field).val())){
							$(this).addClass(o.alertClass);
							valid = false;
							error = "*Phone number must have 10 digits.";
						}
					}
				});
				$(".email").each(function(){
					field = $(this).find("input");
					if(field.val()){
						if(!isValidEmail($(field).val())){
							$(this).addClass(o.alertClass);
							valid = false;
							error = "*Please enter a valid email address.";
						}
					}
				});	
				
				if (!valid) {
				    /* REMOVE OMNITURE TRACKING
					$.ajax({
			            type: 'GET',
			            url: '/global/js/omniture/s_code.js',
			            dataType: 'script',
			            success: function(script) {
							$.fn.setOmnitureValues();
							s.pageName="vwhype:upcomingconcept:submit_error";
						 	s.server=vwServerName;
						 	s.domain=vwDomain;
						 	s.channel="promotional"
						 	s.prop24="upcomingconcept"
						 	s.eVar24="upcomingconcept"

			            },
			            error: function(e) {
				            //alert(e);
			            }
		            });
		            */
		            //alert('Please enter required fields and a valid zip code/email address.');
		            addWarning(error);
					return false; 
				} else {
					// $("#Warning").remove();
					//clearWarning();
					return true;
				}
			});
			
			function clearWarning() {
				$(o.warningPlacement).html("");
				$('#required_1').css("visibility","visible");
			}
			
			function addWarning(msg) {
				$(o.warningPlacement).html("<span id='Warning' style='color: red;font-size:11px;'>"+msg+"</span>");
				$('#required_1').css("visibility","hidden");
			}

		}); 
	}; 

	// plugin defaults 
	$.fn.validatehand.defaults = { 
		requiredClass: 'required',
		alertClass: 'error',
		submitId: '#submitSignUp',
		warningPlacement: '#message-error',
		formParentId: '#accordion-stay-in-the-tdi-loop'
	}; 

var gHandraiserSubmitted = false;
$.fn.bindSignupFormHand = function() {
	$('#signup').submit(function() {
		$this = $(this);
		var ajaxGetURL = $this.attr('action');
		var firstName = $('input#first_name').val();
		var lastName = $('input#last_name').val();
		var zipCode = $('input#zip_code').val();
		var emailAddress = $('input#email_address').val();
		var mobileNumber = $('input#mobile_number').val();
		var params = "xml=<lead><requestType>newsletter</requestType><contact><firstName>" + firstName + "</firstName><lastName>" + lastName + "</lastName><email1>" + emailAddress + "</email1><phone>" + mobileNumber + "</phone><postalCode>" + zipCode + "</postalCode></contact><newsletters><campaign><campaignId>32</campaignId></campaign></newsletters></lead>";
        var crossDomainProxyURL = "http://" + window.location.host + "/hr-curl.php?action=www.vw.com%2Fdealer%2FProcessLead.do&method=get&data1=101&data2=pass";
		
		if(!gHandraiserSubmitted) {
		gHandraiserSubmitted = true;
		$.ajax({
			type: 'GET',
			data: params,
			//url: 'http://72.4.115.43/hr-curl.php?action=www.vw.com%2Fdealer%2FProcessLead.do&method=get&data1=101&data2=pass',
			url: crossDomainProxyURL,
			success: function(xml, strStatus) {
			    //alert('Thank you for signing up!  We\'ll send you some updates soon.');
			    $('#message-error').html("<span id='Warning' style='color: White;font-size:11px;'>Thank you!!!  We'll send you some updates soon.</span>");
			    $('#required_1').css("visibility","hidden");
			    $(xml).find('leadId').each(function() { 
			        // alert($(this).text());
			    });
			    
				//alert("!");
			    
				var emailAddress = $('input#email_address').val();
				var firstName = $('input#first_name').val();
				
				$.ajax({
					type: 'POST',
					data: "email_address=" + emailAddress + "&first_name=" + firstName,
					url: '/wp-content/phpsnippets/vw_tdi_welcome.php',
					success: function() {
						//alert("sent it");
					/*	DO OMNITURE BUSINESS HERE
						$.ajax({
				            type: 'GET',
				            url: '/global/js/omniture/s_code.js',
				            dataType: 'script',
				            success: function(script) {
								$.fn.setOmnitureValues();
								s.pageName="vwhype:upcomingconcept:gti:submit";
							 	s.server=vwServerName;
							 	s.domain=vwDomain;
							 	s.channel="promotional"
							 	s.prop24="upcomingconcept"
							 	s.eVar24="upcomingconcept"

				            },
				            error: function(e) {
					            alert(e);
				            }
			            }); */
						$('#first_name').val('');
						$('#last_name').val('');
						$('#zip_code').val('');
						$('#email_address').val('');
						$('#mobile_number').val('');
					},
					error: function(e) {
						alert(e);
					}
				});
				
				
			},
			error: function(e) {
			    $('#message-error').html("<span id='Warning' style='color: red;font-size:11px;'>"+e.statusText+"</span>");
			    //alert(e.statusText);
			}
		});
		}

		return false;
	});
};
	
$.fn.bindSignupFormHand();
$(".form-stay-in-the-tdi-loop").validatehand();
});

function remove_buttons_for_guinness_row(row) {
	row.children(".vote").html('<span>&nbsp;</span>').removeClass('vote');
}
function stop_accordian_click_event_for_guinness_row(row) {
	row.click(function(e){ e.stopPropagation();}).next().html('');
}
function add_hover_state_for_button(button) {
	button.css('background-position','0 -112px').children("span").css('background-position','right -140px');
}
function remove_hover_state_for_button(button) {
	button.css('background-position','0 0').children("span").css('background-position','right -28px');
}
function add_active_state_for_button(button) {
	button.css('background-position','0 -224px').children("span").css('background-position','right -252px');
}
function remove_active_state_for_button(button) {
	button.css('background-position','0 0').children("span").css('background-position','right -28px');
}