if ( typeof(window.mb)=="undefined"){ mb={}; }

var ie6 = ($.browser.msie && $.browser.version == '6.0') ? true : false;

/**
 * contact us
 */
mb.contactus = new ( function($) 
		{
	var me = this;
	var GA_LOADED = false;
	mb.broadcaster.addListener( mb.events.INITED, function() { mb.contactus.init(); });
	var optinInitState = new Object();
	var subsection;
	/**
	 * must be call by application
	 */
	me.init = function(d)
	{
		mb.logger.log("contactus.init()");
		mb.broadcaster.addListener( mb.events.FRAGMENT_LOADED, function(d){mb.contactus.onFragmentLoaded(d); });
		mb.broadcaster.addListener( mb.events.PAGE_LOADED, function(d){mb.contactus.onPageLoaded(d); });
		mb.broadcaster.addListener( mb.events.ACCORDION_SETUP_COMPLETE, function(d){mb.contactus.onAccordionSetup(d); });
	};


	me.onPageLoaded = function( d ) 
	{
		var node = d.getNode();
		var section = d.getProperty('section');
		subsection = d.getProperty('subsection');
		var contextPath = d.getProperty("contextPath");

		// trigger the form change handler
		$("#contact-email-select").change( function(){

            var selection = $(this).val();

            //AB: Once all forms are updated to modal mechanisms, logic can be removed
            if(selection.indexOf("inquiry") > 0 || selection.indexOf("general") > 0 || selection.indexOf("classic") > 0 || selection.indexOf("owners") > 0){
                mb.contactforms.launchForm(selection);

            } else {

			    window.location.href = $(this).val();
            }

		});

		// Handle Brochure-PDF link checks
		$(".brochure-pdf-check").each(function() {
			var link = $(this);
			$.ajax({
				type: "HEAD",
				url : $(this).attr("href"),
				success: function () {
					console.log("****success..file found******");
					$(link).show();
				},
				error: function (){ 
					console.log("****error..file not found******");
					$(link).hide(); 
					if($(link).parent().hasClass("brochure"))
					{
						$(link).parent().hide();
					}
				}
			});
		});



        if (section == "contactus") {

			var esmSection = $(".page-properties .esm-section").text();
			if(esmSection == 'contact_us/classic_center'){
				$("#esm-body .esm-category-group").css("padding-bottom","110px");
				$(".contactus .subnavigation").addClass('classic-center-esm');
			}

			if (subsection == "overview") {
				$('.section-group.side-bar').height($('.section-group').eq(0).height() + 100);
					}
			else if (subsection == "faqs") {
				//unbind click from open/close all container before firing the click
				$(".faqs-print a").unbind("click").click(function(){
					return true;
				});
			}

			//Email Subscription Management
			else if (subsection == "esm" || subsection == "manage_optin_status") {	

				mb.contactus.disableUnsubscribe();

				//Save optin category init state
				$('#esm-form div.optin-init').each(function(){
					optinInitState[$.trim($(this).text())] = ($(this).attr('checked') == undefined ?"false":$(this).attr('checked'));
				});

				if(subsection == "esm" && !GA_LOADED)
				{
					mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":"ESM-ContactUs","action":"ESM-OptinStart","label":""});
					GA_LOADED = true;
				}

				//Manage Subscription button (landing Page) - show the input box
				$("#manage-subscriptions").click(function(){
					$(this).hide();
					$(".esm-active-state .esm-form-controls").show();

				});

				//Show the error message if the email address does not exist in db
				if($('.esm-form-controls').find('span.error').size() > 0)
				{
					$("#manage-subscriptions").hide();
					$(".esm-active-state .esm-form-controls").show();
					$('#manage-interests-form .esm-email').addClass('error');
				}

				//enabling update button 
				$(".esm-category-group .esm-category input").click(function(){
					$('#update-subscriptions').attr('disabled',false);
					$('#update-subscriptions').removeClass('esm-button-disabled-state');	
					mb.contactus.disableUnsubscribe();
				});


				//Unsubscribe all link handler in manage interests page
				$("#unsubscribe-all a").click(function(){	
					if($("#esm-form .esm-category-group .esm-category input[type='checkbox']:checked").size() == 0 || $('#unsubscribe-all a').hasClass('esm-button-disabled-state'))
					{
						return false;
					}
					else{
						//$("#esm-form .esm-category-group input:checkbox").removeAttr('checked');
						$("#esm-form").attr("action",$(this).attr('href'));
						$("#global-optin").val("O");
						$("#esm-form").submit();
						return false;
					}

				});

				//cancel link
				$(".esm-cancel").click(function(){
					$("#esm-form .esm-form-controls").hide();
					$(".update-optin-status .esm-form-controls input.esm-email").val($(".esm-change-email input[name='oldEmail']").val());
					$(".esm-change-email").show();
					return false;
				});

				//Change email address action in manage interests form
				$(".esm-change-email a").click(function(){
					$(".esm-change-email").hide();
					$("#esm-form .esm-form-controls").show();
					$('#update-subscriptions').attr('disabled',false);
					$('#update-subscriptions').removeClass('esm-button-disabled-state');
					$("#esm-form").attr("action",contextPath + "/" + esmSection + "/mercedes_email_subscription/subscribe/change");					
				});

				$(".esm-email").click(function(e){
					if($(this).val() == 'Enter your email address')
					{
						$(this).val("");
					}
				});


				//ESM form validate
				$("#esm-form").validate({
					onfocusout: false,
					onkeyup: false,
					rules : {
						email : {
							required: true,
							email: true
						}
					}
				,messages: {
					email : {
						required: "Please enter your email address.",
						email: "Please enter a valid email address"
					}
				}
				,errorPlacement: function(error, element) {
					$('#esm-form .esm-form-controls .esm-errors').html(error);
				}
				,submitHandler : function(form) {

					//No optin category selected
					if($('#esm-form .esm-category input:checked').size() == 0 || $("#global-optin").val() == "O")
					{
						//If subscribe action in landing page, throw error message
						if(subsection == "esm")
						{
							$('.esm-form-controls #email').addClass('error');
							$('#esm-form .esm-form-controls .esm-errors').html("<label class='error'>Please select at least one email category</label>");
							return false;
						}
						else //Manage Optin page
						{
							/* Change email action - if both old and new email addresses are NOT same and user 
					 			   try to unsubscribe both, create error state */
							if($(".esm-change-email input[name='oldEmail']").val() == $("#esm-form .esm-email").val())
							{
								$("#global-optin").val("O");
								$("#esm-form").attr("action",$("#unsubscribe-all a").attr('href'));
							}
							else
							{
								$('#esm-form .esm-form-controls #email').addClass('error');
								$('#esm-form .esm-form-controls .esm-errors').html("<label class='error'>Please select at least one email category</label>");
								return false;
							}

							//delete esm cookie for unsubscribe action
							$.cookie("MBUSA_ESM_STATUS", null,{ path: '/'});
						}
					}
					else
					{
						//Set the form action back to update (to resolve conflict btw unsubscribe all and update)
						if(subsection == "manage_optin_status")
						{
							if($(".esm-change-email input[name='oldEmail']").val() != $("#esm-form .esm-email").val()){
								$(form).attr("action",contextPath + "/" + esmSection +"/mercedes_email_subscription/subscribe/change");
							}
							else{
								$("#global-optin").val("I");
								$(form).attr("action",contextPath + "/" + esmSection +"/mercedes_email_subscription/update/success");
							}
						}

						//set esm cookie for subscribe/update action
						$.cookie("MBUSA_ESM_STATUS",'1',{ path: '/', expires:new Date( 2042, 1, 1 ) });
					}

					//GA tagging (optins)
					mb.contactus.setOptinGaTag(form, "ESM-ContactUs", subsection);

					if(subsection == "manage_optin_status")
					{
						//set GA unsubscribe tag
						mb.contactus.setOptoutGaTag(form,"ESM-ContactUs");
					}
					form.submit();
					return false;

				}

				});

				$("#manage-interests-form").validate({
					onfocusout: false,
					onkeyup: false,
					rules : {
						email : {
							required: true,
							email: true
						}
					}
				,messages: {
					email : {
						required: "Please enter your email address.",
						email: "Please enter a valid email address"
					}
				}
				,errorPlacement: function(error, element) {
					$('.esm-active-state .esm-form-controls .esm-errors').html(error);
					//clear any back end errors if any.
					$('.esm-active-state .esm-form-controls .esm-errors').next('span.error').html('');
				}

				});
			}


			$("#contact-us.review form").submit( function() { 
				return;
			});
		}
		else if(section == 'homepage') 
		{				
			//to handle optin's when coming from external email link.
			var email = $("#email").val();

			if(email != "")
			{
				window.location = contextPath + "/" + esmSection + '/mercedes_email_subscription/manage/interests?email='+ email;
			}
			else if($("#load-fragment").val() == "manage_subscription")
			{				
				window.location = contextPath + "/" + esmSection +'/mercedes_email_subscription';
			}
		}		
		else if(section == 'themes')
		{
			$("#cc-signup-form").validate({
				onfocusout: false,
				onkeyup: false,
				rules : {
					email : {
						required: true,
						email: true
					}
				}
				,messages: {
					email : {
						required: "Please enter your email address.",
						email: "Please enter a valid email address"
					}
				}
				,errorPlacement: function(error, element) {
					$('#cc-signup-form .esm-errors').html(error);
				}
				,submitHandler : function(form) {
					var dataString = $(form).serialize();
					var url = $(form).attr("action");
					$.ajax({
						type: "POST",
						url : url,
						data: dataString,
						success : function(data, textStatus, XMLHttpRequest) {
							$(form).parents('#signup-container').html(data);
							mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":"ESM-InPage","action":"ESM-Optin","label":"Mercedes-Benz Classic Center Updates"});
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) {
							mb.logger.log('ESM subscribe error:'+errorThrown);
						}
					});
					return false;
				}
			});
		}
	};

	me.onAccordionSetup = function( d ) 
	{
		if (subsection == "faqs") {
			mb.contactus.wireFaqs();
		}
	};
	me.onFragmentLoaded = function( d ) 
	{
		//hack: To fix positioning issue with esm sample overlay
		$('#image-overlay .overlay-image').load(function(){
			mb.modal.positionModal($('.modal-container'));
			var offset = $('.modal-content-wrapper').offset();
			var top = offset.top + 70;
			$('.modal-content-wrapper').css("top",top);
				
		});

		//On fragment loaded.	
		$("#image-overlay").parent().prev('a.close-modal').addClass('image-overlay-close');
		$('.image-overlay-close').html('<span/>');
		$('.image-overlay-close').parent().parent('.modal-container').addClass('esm-overlay');

	};
	
	me.wireFaqs = function(){
		
		var category = $(".page-properties .pp-category").text();
		var faq = $(".page-properties .pp-faq").text();
		if(category != "")
		{
			var pane = $("#"+category+" .accordion-title").eq(0);
			
			if(pane.size()){
				if(!$(pane).parent().hasClass('open'))
				{
					pane.click();
					$("#"+category+" .accordion-nested h4[id="+faq+"]").find('a').attr("id",category + "_" + faq);
					location.href = location.href+"#"+category + "_" + faq;
				}
			}
			
			mb.broadcaster.addListener( mb.events.ACCORDION_TOGGLE, function(e,args){ 
				var pane = $("#"+category+" .accordion-nested h4[id="+faq+"]");
				if(!$(pane).parent().hasClass('bookmark'))
				{
					$(pane).parent().children('.accordion-content').show();
					$(pane).parent().addClass('open bookmark');
				}
	        });

		}
		else
		{
			$('.faqs.uxp2 .accordion .accordion-title:not(.accordion-nested-title)').eq(0).click();
		}
		
	}
	me.setOptinGaTag = function(form, category, subsection)
	{
		var optinLabels = "";
		var winBack = false;
		var optin = false;
		$(form).find('.esm-category input:checked').next('div.esm-cat-details').each(function(i,v){
			var label =$.trim( $(this).find('label').text());	
			if(subsection == "manage_optin_status"){
				if(optinInitState[label] == "false" && $(this).prev('input').is(':checked') == true){
					optinLabels += label+"|"; 
				}
			}
			else{
				optinLabels += label+"|";
			}
			//Winback check : user adds a new newsletter category
			if(!winBack && optinInitState[label] == "false" && $(this).prev('input').is(':checked') == true )
			{
				winBack = true;
				optin = true;
			}	 		
		});
	 	optinLabels = optinLabels.substr(0, optinLabels.length - 1);
	 	if(optinLabels != "")
	 	{
	 		if(winBack)
	 		{
	 			mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":category,"action":"ESM-Winback","label":""});
	 		}
	 		if(subsection == "manage_optin_status"){
		 		if(optin){
		 			mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":category,"action":"ESM-Optin","label":optinLabels});
		 		}
	 		}
	 		else{
	 			mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":category,"action":"ESM-Optin","label":optinLabels});
	 		}
	 	}
	}

	me.setOptoutGaTag = function(form, category)
	{
		var optOuts = "";
		$(form).find('.esm-category input').each(function(){
			var label = $.trim($(this).next('.esm-cat-details').find('label').text());
			if(optinInitState[label] == "true" && $(this).is(':checked') == false )
			{
				optOuts +=label + "|"
			}
		});

		optOuts = optOuts.substr(0, optOuts.length - 1);
		if(optOuts != "")
		{
			mb.metrics.trackInteraction({"type":"GA","trackType":"_trackEvent","category":category,"action":"ESM-Unsubscribe","label":optOuts});
		}

	}


	me.disableUnsubscribe = function(){
		if($("#esm-form .esm-category-group .esm-category input[type='checkbox']:checked").size() == 0){
			$('#unsubscribe-all a').addClass('esm-button-disabled-state');
			$('#unsubscribe-all a').removeClass('blue-carat');

		}
		else{			
			$('#unsubscribe-all a').removeClass('esm-button-disabled-state');
			$('#unsubscribe-all a').addClass('blue-carat');
		}

	};
})(jQuery);

