/* Author: Matt Bower

*/

(function($) {
    $(function() {
		// Leverage HTML5 Boilerplate to browser sniff
		var root = $('html').eq(0),
			isIE6 = root.hasClass('ie6'),
			isIE7 = root.hasClass('ie7'),
			isIE8 = root.hasClass('ie8'),
	
			$galleries = $('#content').find('.photo_gallery');
	
		if(isIE8 || isIE7 || isIE6) $('#mainnav li:last').addClass('last');
	
        // var $login_info = $('#login_details, #register_form');
        var $login_info = $('#register_form');
		if($login_info.length) {
			$('#username', $login_info).parent('div').after('<div class="form-field"><label for="username_confirm"><span class="required-star">*</span>Confirm Email Address</label><input type="text" name="username_confirm" id="username_confirm" class="text " value="" /></div>');
		}

		// Split up product listing into 2 columns on Job Details form
		var $jd_form_opts = $('#job_details').find('fieldset.options'),
			opts = $jd_form_opts.find('li').get();
		
		$jd_form_opts.children('ul').remove();
		
		$('<ul class="column" />').append(opts.splice(0, (opts.length/2)+1)).appendTo($jd_form_opts);
		$('<ul class="column" />').append(opts).appendTo($jd_form_opts);
		
		// Fallback support for input placeholder
		if(!Modernizr.input.placeholder) {
			$('input[placeholder]').each(function(idx, el) {
				var $el = $(el),
					txt = $el.attr('placeholder');

				if($el.val() === '') $el.val(txt);
				$el.bind('focus', function(ev) {
					if($el.val() === txt) $el.val('');
				}).bind('blur', function(ev) {
					if($el.val() === '') $el.val(txt);
				});
			});
		}

		
		
		//Accordion Menu
		// $('.menu li ul li ul').hide();
		// $('.menu li ul li ul').click(function() {
		// 	$('.menu li ul li ul').hide();
		// 	$(this).slideDown();
		// });

		
		// Galleria
		if(!isIE6 && $galleries.length && window.Galleria) {
			Galleria.loadTheme('/assets/js/galleria/themes/augi/galleria.augi.js');
			$galleries.addClass('js_photo_gallery').galleria();
		}
		
		// Make sure the Remove [Image] buttons on the account pages do a JS confirm
		$('.remove_btn').bind('click', function(ev) {
			return window.confirm('Are you sure you want to delete this image?');
		});
		
		//US/Canada postal code validation
		jQuery.validator.addMethod("pc", function(value, element) {
			var mc = $("#cf_member_country").selectedValues();
			if (mc == 'United States' || mc == 'Canada') {
				return value.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} \d{1}[A-Z]{1}\d{1})$/);
			} else {
				return true;
			}
		}, "Please specify a valid postal code");
		
		//US phone validation
		jQuery.validator.addMethod("phoneUS", function(value, element) {
			var mc = $("#cf_member_country").selectedValues();
			if (mc == 'United States') {
		    	value.replace(/\s+/g, ""); 
				return value.length > 9 &&
					value.match(/^\(?[2-9]\d{2}\)? \d{3}-?\d{4}$/);
				} else {
					return true;
				}
		}, "Please specify a valid phone number");
		
		//jQ Validate
		$('#account_update').validate({
			rules: {
				username: {
					email: true,
					required: true
				},
				cf_member_first_name: "required",
				cf_member_last_name: "required",
				cf_member_country: "required",
				cf_member_address1: "required",
				location: "required",
				cf_member_mylanguage: "required",
				cf_member_industry: "required",
				cf_member_market: "required",
				cf_member_job_function: "required",
				occupation: "required",
				cf_member_phone: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'United States';
						},
						phoneUS: true
					},
				cf_member_state: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'United States';
						}
					},
				cf_member_province: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'Canada';
						}
					},
				cf_member_postal_code: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'United States' || mc == 'Canada';
						},
						pc: true
					}
			},
			submitHandler: function(form) {
				if (!$('#account_update').find('input:checked').length) {
					$('p.product-alert').show();
					return false;
				}
			form.submit();
			}
		});
		
		//extra help on autodesk products
		$('#account_update input[type=checkbox]').live('click', function() {
			if(this.checked) {
				$(this).val('y').attr('checked','checked');
			} else {
				$(this).val('').removeAttr('checked');
			}
		});
	
		//caps for postal code
		$('#cf_member_postal_code').blur(function() {
			var pc = $(this).val();
			$(this).val(pc.toUpperCase());
		});
		
		//format phone number
		$('#cf_member_phone').blur(function() {
			var country = $('#cf_member_country').selectedValues();
			if(country == 'United States') {
				var phone = $(this).val();
				phone = phone.replace(/[^0-9]/g,'');
				if (phone.length != 10) {
					//remove 1 if its the first number
					if(phone.charAt(0) == '1') {
						phone = phone.substr(1);
						phone = phone.substr(0,10);
					}
				}
				area = phone.substring(0,3);
				prefix = phone.substring(3,6);
				line = phone.substring(6);
				if ((area+prefix+line).length > 0) {
					$(this).val('(' + area + ') ' + prefix + '-' + line);
				} else {
					$(this).val('');
				}
			}
		});
/////		
		$('#login_details').validate({
			rules: {
				username: {
					email: true,
					required: true
				},
				password: {
					minlength: 5
				},
				password_confirm: {
					required: function(el) {
						return $('#password').val().length > 0;
					},
					minlength: 5,
					equalTo: "#password"
				},
				current_password: {
					required: true
				}
			},
			messages: {
				password: {
					minlength: 'Minimum length is 5 characters.'
				},
				password_confirm: {
					minlength: 'Minimum length is 5 characters.',
					equalTo: 'Your new password fields do not match.'
				}
			}
		});

		$('#register_form').validate({
			rules: {
				username: {
					required: true,
					email: true
				},
				username_confirm: {
					required: true,
					email: true,
					equalTo: "#username"
				},
				cf_member_first_name: "required",
				cf_member_last_name: "required",
				password: {
					required: true,
					minlength: 5
				},
				password_confirm: {
					required: true,
					minlength: 5,
					equalTo: "#password"
				},
				cf_member_country: "required",
				cf_member_industry: "required",
				cf_member_reg_product: "required",
				captcha: "required",
				accept_terms: "required",
				cf_member_state: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'United States';
						}
					},
				cf_member_province: {
						required: function(element) {
							var mc = $("#cf_member_country").selectedValues();
							return mc == 'Canada';
						}
					}
			},
			messages: {
				username: {
					email: 'Please enter a valid email address.'
				},
				username_confirm: {
					email: 'Please enter a valid email address.',
					equalTo: 'This must match your email address above.'
				},
				password: {
					minlength: 'Your password must be a minimum of 5 characters.'
				},
				password_confirm: {
					minlength: 'Your password must be a minimum of 5 characters.',
					equalTo: 'This must match your password above.'
				},
				captcha: {
					required: 'Please enter the numbers and letters you see above.'
				},
				accept_terms: {
					required: 'You must check the box to accept the AUGI.com Terms and Conditions.'
				}
			},
			errorPlacement: function(err, el) {
				if(el.attr('name') == 'accept_terms') el.parent('div').children('label').after(err);
				else el.after(err);
			}
		});
		
		$('#recover_password').validate({
			rules: {
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				email: {
					required: 'You must enter your email address to recover your password.',
					email: 'Please enter a valid email address.'
				}
			}
		});

		
		$('#profile_settings').validate({
			rules: {
				cf_member_profile_url_segment: {
					remote: {
						url: '/api/profile_url_unique/',
						type: 'post'
					}
				}
			},
			messages: {
				cf_member_profile_url_segment: {
					remote: 'This URL suffix is already taken.'
				}
			}
		});
		
		// $('#first_time_login').validate({
		// 	rules: {
		// 		screen_name: {
		// 			required: true,
		// 			remote: {
		// 				url: '/api/screenname_unique/',
		// 				type: 'post'
		// 			}
		// 		},
		// 		cf_member_profile_url_segment: {
		// 			required: true,
		// 			remote: {
		// 				url: '/api/profile_url_unique/',
		// 				type: 'post'
		// 			}
		// 		}
		// 	},
		// 	messages: {
		// 		screen_name: {
		// 			required: 'Please choose a Forum Nickname.',
		// 			remote: 'That nickname is already taken.'
		// 		},
		// 		cf_member_profile_url_segment: {
		// 			required: 'Please choose a Profile URL Suffix.',
		// 			remote: 'That suffix is already taken.'
		// 		}
		// 	},
		// 	onkeyup: false
		// });
		
		$('#first_time_login').validate({
			rules: {
				cf_member_accept_terms: "required"
			}
		});
		
		$('#nickname_form').validate({
			rules: {
				new_name: {
					required: true,
					remote: {
						url: '/api/screenname_unique/',
						type: 'post',
						data: {
							new_name: function() {
							return $("#new_name").val();
							}
						}
					}
				}
			},
			messages: {
				new_name: {
					required: 'Please choose a Forum Username.',
					remote: 'That Username is already taken or contains invalid characters.'
				}
			}
		});
		
		$('#login_form').validate({
			rules: {
				username: {
					required: true,
					email: true
				},
				password: "required"
			}
		});
		
		
		$('#job_details').validate({
			rules: {
				cf_member_company_name: 'required',
				occupation: 'required',
				cf_member_industry: 'required',
				cf_member_job_function: 'required',
				cf_member_begin_cad: 'required',
				cf_member_purchase_authority: 'required',
				cf_member_number_of_applications: 'required',
				cf_member_number_of_users: 'required',
				cf_member_subscription_customer: 'required',
				cf_member_autodesk_products: 'required'
			},
			messages: {
				cf_member_company_name: {
					required: 'Please enter your employer.'
				},
				occupation: {
					required: 'Please enter your position title.'
				},
				cf_member_industry: {
					required: 'Please select your industry affiliation.'
				},
				cf_member_job_function: {
					required: 'Please select your job function.'
				},
				cf_member_begin_cad: {
					required: 'Please select when you started using CAD.'
				},
				cf_member_purchase_authority: {
					required: 'Please select how you are involved in purcahsing CAD software.'
				},
				cf_member_number_of_applications: {
					required: 'Please select how many CAD applications are in use in your organization.'
				},
				cf_member_number_of_users: {
					required: 'Please select how many CAD users there are in your organization.'
				},
				cf_member_subscription_customer: {
					required: 'Please select if you or your firm are subscription customers.'
				},
				cf_member_autodesk_products: {
					required: 'Please select which Autodesk products are used in your organization.'
				}
			},
			errorPlacement: function(err, el) {
				if(el.attr('name') == 'cf_member_autodesk_products') el.parents('ul').before(err);
				else el.after(err);
			}
		});
		
		$('#wish_form').validate({
			rules: {
				"category[]": "required",
				"wish-summary": "required",
				"wish-full-description": "required",
				"title": "required"
			}
		});
		
		$('#new_wish_search').validate({
			rules: {
				"category[]": "required",
				title: "required"
			}
		});
		
		$('#wish_report_form').validate({
			rules: {
				"wish-report-notice": "required"
			}
		});
		
		// faq pages
		$('#faqlist li div').hide();
		$('#faqlist li h3').click(function() {  
			var $parent = $(this).parent();
			$(this).next().slideToggle("fast");
			if( $parent.is('.closed') ) {
				$parent.removeClass('closed');
				$parent.addClass('open');
			} else {
				$parent.removeClass('open');
				$parent.addClass('closed');
			}
		});
		
		//voting help
		$('.click-more a').click(function() {
            $('tr.less').hide();
            $('tr.more').show();
        });

		//atp more info reveal
		$('.atp-course h3').toggle(function() {
			$(this).parents('div').children('.more-info').slideDown('fast');
		}, function() {
			$(this).parents('div').children('.more-info').slideUp('fast');
		});
		
		//profile update
		//country, state, province
		$('#cf_member_country').change(function() {
			country_driver();
		});
		
		//hide 
		$('#register_form #ff-region, #register_form #ff-province').hide();
		
		//unsubscribe all
		$('#optout').click(function() {
			if ($(this).is(':checked')) {
				$('#email_subscriptions input[value="n"]').not(this).click();
				$('#cf_member_optout').val('n');
			} else {
				$('#email_subscriptions input[value="y"]').not(this).click();
				$('#cf_member_optout').val('y');
			}
		});

		//feedback box hide
		//$(".feedback").delay(3000).slideUp(300);
		
		$('.wish-retract').click(function() {
			if (confirm("Are you sure you want to retract this wish?")) {
				return true;
			} else {
				return false;
			}
		});
		
		$('.btn-wish-report').click(function() {
			if (confirm("Are you sure you want to report this wish?")) {
				return true;
			} else {
				return false;
			}
		});
		
		$('.wish-granted-link').click(function() {
			if (confirm("Are you sure this wish has been granted?")) {
				return true;
			} else {
				return false;
			}
		});
		
		
		
		
		
		
		
		//Page manipulation for BoD voting
		
		$('.bod_vote_form input[type=checkbox]').change(function() {
			var $input = $(this);
			//get the entry ID from the checkbox
			var entry_id = $input.attr('rel');

			//is the checkbox checked now?
			if($input.is(':checked')) {
				//turn it green
				$input.parents('tr').find('h3').css('color','green');
				$input.parents('tr').find('img').css('border-color','green');
				//decrement the counter
				var num_votes = $('.num-votes span').text();
				num_votes = parseInt(num_votes);
				num_votes = num_votes-1;
				//turn the header color
				if(num_votes == 0) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>0</span> votes remaining! Thanks for voting!</p>');
					$('.num-votes').css('color','#f00');
					$('.num-votes').css('width','330px');
					//disable the rest of the checkboxes
					$(".bod_vote_form input[type=checkbox]:not(:checked)").each(function() {
						$(this).attr('disabled',true);
					});
				} else if(num_votes == 1) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>1</span> vote remaining!</p>');
					$('.num-votes').css('color','#c60');
					$('.num-votes').css('width','200px');
				} else {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>'+num_votes+'</span> votes remaining!</p>');
					$('.num-votes').css('color','green');
				}

			} else { //not checked
				//turn it black
				$input.parents('tr').find('h3').css('color','inherit');
				$input.parents('tr').find('img').css('border-color','#ddd');
				//increment the counter
				var num_votes = $('.num-votes span').text();
				num_votes = parseInt(num_votes);
				num_votes = num_votes+1;
				//turn the header color
				if(num_votes == 0) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>0</span> votes remaining! Thanks for voting!</p>');
					$('.num-votes').css('color','#f00');
					$('.num-votes').css('width','330px');
				} else if(num_votes == 1) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>1</span> vote remaining!</p>');
					$('.num-votes').css('color','#c60');
					$('.num-votes').css('width','200px');
					//enable the rest of the checkboxes
					$(".bod_vote_form input[type=checkbox]:not(:checked)").each(function() {
						$(this).attr('disabled',false);
					});
				} else {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>'+num_votes+'</span> votes remaining!</p>');
					$('.num-votes').css('color','green');
				}
			}

		});
		
		
		//Ajax submit for BoD vote groups

		$('#bod-submit').click(function(e) {
			e.preventDefault();
			var url = 'http://dev.augi.com'+$(this).attr('rel');
			var $checked = $('.bod_vote_form input[type=checkbox]:checked').parents('form');
			var length = $checked.length;
			$checked.each(function(i,val) {
				$(this).ajaxSubmit();
			});
		});

		
		
		
		
		
		
		
		
		// Wish List stuff


		//Ajax submit for wish vote groups
		
		$('.wish_vote_form input[type=checkbox]').change(function() {
			var $input = $(this);
			//get the entry ID from the checkbox
			var entry_id = $input.attr('rel');

			//is the checkbox checked now?
			if($input.is(':checked')) {
				//ajax submit the form
				$('#rating_form'+entry_id).ajaxSubmit();
				//turn it green
				$input.siblings('span').css('color','green');
				//decrement the counter
				var num_votes = $('.num-votes span').text();
				num_votes = parseInt(num_votes);
				num_votes = num_votes-1;
				//turn the header color
				if(num_votes == 0) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>0</span> votes remaining! Thanks for voting!</p>');
					$('.num-votes').css('color','#f00');
					$('.num-votes').css('width','330px');
					//disable the rest of the checkboxes
					$(".wish_vote_form input[type=checkbox]:not(:checked)").each(function() {
						$(this).attr('disabled',true);
					});
				} else if(num_votes == 1) {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>1</span> vote remaining!</p>');
					$('.num-votes').css('color','#c60');
					$('.num-votes').css('width','200px');
				} else {
					$('.num-votes').replaceWith('<p class="num-votes">You have <span>'+num_votes+'</span> votes remaining!</p>');
					$('.num-votes').css('color','green');
				}
				
			} else { //not checked
				$.ajax({
					url: '/_ajax/delete_wish_vote/rating/'+entry_id,
					success: function(data) {
						//turn it black
						$input.siblings('span').css('color','inherit');
						//increment the counter
						var num_votes = $('.num-votes span').text();
						num_votes = parseInt(num_votes);
						num_votes = num_votes+1;
						//turn the header color
						if(num_votes == 0) {
							$('.num-votes').replaceWith('<p class="num-votes">You have <span>0</span> votes remaining! Thanks for voting!</p>');
							$('.num-votes').css('color','#f00');
							$('.num-votes').css('width','330px');
						} else if(num_votes == 1) {
							$('.num-votes').replaceWith('<p class="num-votes">You have <span>1</span> vote remaining!</p>');
							$('.num-votes').css('color','#c60');
							$('.num-votes').css('width','200px');
							//enable the rest of the checkboxes
							$(".wish_vote_form input[type=checkbox]:not(:checked)").each(function() {
								$(this).attr('disabled',false);
							});
						} else {
							$('.num-votes').replaceWith('<p class="num-votes">You have <span>'+num_votes+'</span> votes remaining!</p>');
							$('.num-votes').css('color','green');
						}

					}
				});
			}

		});

    });


})(jQuery);


$(document).ready(function(){
	$("#jSearch").click(function(){
			$(this).parents('.ff-wl').children('.spinner').show();
			var $data = $("#jtitle").val();
			var $product = $("#jProduct").val();

			if($data.length<3)
			{
			return;
			}

			if($product.length<1)
			{
			return;
			}

			var $url = "/_ajax/"+$data+"/"+$product;
			
			$.getJSON($url,function(d){
				var $count = 0;
				
				$("#wish-listing tr").remove();
				$("#wish-listing").append("<tr><th class='title'>Wish Title</th><th class='product'>Product</th></tr>");
				
				$.each(d, function(i,val){

					if(i!=0){
						if(val['mode']=="edit")
						{
						$("#wish-listing").append("<tr><td class=\"title\"><a href='/wishlist/rank/edit/"+i+"'>"+val['title']+"</a></td><td class='product'>"+val['cat']+"</td></tr>");
						}
						else
						{
						$("#wish-listing").append("<tr><td class=\"title\"><a href='/wishlist/direct-rank/"+i+"' target=\"_blank\">"+val['title']+"</a></td><td class=\"product\">"+val['cat']+"</td></tr>");
						}

					$count++;
					}
					
					
				});
				
				if ($count==0)
				{
					$("#wish-listing th").remove();
					$("#wish-listing").append('<tr><td colspan="3" class="no-wish-results">No wishes were found for those keywords. Please try again or <a href="#" id="newwish">Add a New Wish</a>.</td></tr>');
				}
				else
				{
				$("#wish-listing").append('<tr><th colspan="3" class="no-wish">Don\'t see your wish here? <a href="#" id="newwish">Add a New Wish</a></th></tr>');
				}
				$('.spinner').hide();
			}
			);
			
		});
		
$("#newwish").live('click',function(){
			$("#searchcontainer").slideUp('slow');
			$("#addwish").slideDown('slow');
			
			//$("#title").val($("#jtitle").val());
			$("#product").val($("#jProduct").val());
			
			getfeatures($("#product").val());
			
			return false;
		});
		
		$("#product").change(function(){
			getfeatures($(this).val());
		});
		
		$('#wish-edit-features').live('load',function() {
			wisheditfeatures($("#product").val());
			
			return false;
		});
});


function featurepop(d)
{
				$("#features").find("option").remove();
				
				$.each(d,function(i,val){
					if (i!=0)
					{
						$("#features").append("<option value='"+val['catid']+"'>"+val['catname']+"</option>");
					}
				});
				
				//$("#features").val($sel);
}

function getfeatures($data,$sel)
{
$.getJSON("/_ajax/prodfeatures/"+$data,function(d){
	$("#features").find("option").remove();
				
				$.each(d,function(i,val){
					if (i!=0)
					{
						$("#features").append("<option value='"+val['catid']+"'>"+val['catname']+"</option>");
					}
				});
				$("#features").val($sel);
});
}


function wisheditfeatures($data)
{
	$.getJSON("/_ajax/prodfeaturesedit/"+$data,'',function(d){
					$("#features").find("option").remove();
alert($data);
					$.each(d,function(i,val){
						if (i!=0)
						{
							$("#features").append("<option value='"+val['catid']+"'>"+val['catname']+"</option>");
						}
					});
				});	
}



function country_driver() {
	var country = $("#cf_member_country").selectedValues();
	if(country == 'United States') {
		$("#ff-state").show();
		$("#ff-province").hide();
		$("#ff-region").hide();
		$(".cfm_pc").html('*');
		$(".cfm_phone").html('*');
	} 
	else if(country == 'Canada') {
		$("#ff-state").hide();
		$("#ff-province").show();
		$("#ff-region").hide();
		$(".cfm_pc").html('*');
		$(".cfm_phone").html('');
	}
	else {
		$("#ff-state").hide();
		$("#ff-province").hide();
		$("#ff-region").show();
		$(".cfm_pc").html('');
		$(".cfm_phone").html('');
	}
}
