﻿$(function(){
		   $ncf.init();
});

var $ncf = function($)
{
	function initAll()
	{
		   initHovers();
		   initClicks();
		   initHide();
		   initClueTips();
		   initValidators();
		   initScroll();
		   loadFunds();
	}
	
	function initScroll()
	{
		if(window.location.hash == "#malspara") {
			$("#step1").hide();
			$("#step10").show();
			$.scrollTo("#step10", 10);
			step10();
			return;
		}
		$.scrollTo("#step1", 10);
		step1();
	}
	
	function applyForMalsparaState()
	{
		$("div.customerButtonContainer a").attr("href", "/borja_spara_nu_s310.html#malspara");
		$("div.customerButtonContainer img.customerButton").attr("class", "malsparaButton");
		$("div.customerButtonContainer img.malsparaButton").attr("src", "/images/buttons/borja-malspara.png");
		$("div.customerButtonContainer img.malsparaButton").hover(function(){$(this).attr("src", "/images/buttons/borja-malspara-hover.png");}
									, function(){$(this).attr("src", "/images/buttons/borja-malspara.png");}
									);
	}
	function applyForOriginalState()
	{
		$("div.customerButtonContainer a").attr("href", "/borja_spara_nu_s310.html#pensionsspara");
		$("div.customerButtonContainer img.malsparaButton").attr("class", "customerButton");
		$("div.customerButtonContainer img.customerButton").attr("src", "/images/buttons/customer.png");
		$("div.customerButtonContainer img.customerButton").hover(function(){$(this).attr("src", "/images/buttons/customer_hover.png");}
									, function(){$(this).attr("src", "/images/buttons/customer.png");}
									);
	}
	
	function initHovers()
	{
		if(window.location.hash == "#malspara") {
			applyForMalsparaState();
		}
		$("#step1btn1,#step1btn3").hover(   function(){$(this).attr("src", "/images/newcustomerform/right_button_hover.png");}
																, function(){$(this).attr("src", "/images/newcustomerform/right_button.png");}
																);
		$("#step1goto2block").hover(  function(){$("#step1goto2").attr("src", "/images/newcustomerform/right_button_hover.png");}
									, function(){$("#step1goto2").attr("src", "/images/newcustomerform/right_button.png");}
									);
		$("#step1btn4block").hover(   function(){$("#step1btn4").attr("src", "/images/newcustomerform/right_button_hover.png");}
									, function(){$("#step1btn4").attr("src", "/images/newcustomerform/right_button.png");}
									);
		$("#step2goto3,#step3goto4,#step4goto5").hover(   function(){$(this).attr("src", "/images/newcustomerform/right_button_hover.png");}
														, function(){$(this).attr("src", "/images/newcustomerform/right_button.png");}
														);
		$("#step2goto1,#step3goto2,#step4goto3,#step5goto4").hover(   function(){$(this).attr("src", "/images/newcustomerform/left_button_hover.png");}
														, function(){$(this).attr("src", "/images/newcustomerform/left_button.png");}
														);
		$("#step2goto3map").hover(  function() {$("#step2tab").attr("src", "/images/newcustomerform/step2_step3.jpg");}
								  , function() {$("#step2tab").attr("src", "/images/newcustomerform/step2.jpg");}
								  );
		$("#step3goto2map").hover(  function() {$("#step3tab").attr("src", "/images/newcustomerform/step3_step2.jpg");}
								  , function() {$("#step3tab").attr("src", "/images/newcustomerform/step3.jpg");}
								  );
		$("#step3goto4map").hover(  function() {$("#step3tab").attr("src", "/images/newcustomerform/step3_step4.jpg");}
								  , function() {$("#step3tab").attr("src", "/images/newcustomerform/step3.jpg");}
								  );
		$("#step4goto3map").hover(  function() {$("#step4tab").attr("src", "/images/newcustomerform/step4_step3.jpg");}
								  , function() {$("#step4tab").attr("src", "/images/newcustomerform/step4.jpg");}
								  );
		$("#step4goto5map").hover(  function() {$("#step4tab").attr("src", "/images/newcustomerform/step4_step5.jpg");}
								  , function() {$("#step4tab").attr("src", "/images/newcustomerform/step4.jpg");}
								  );
		$("#step5goto4map").hover(  function() {$("#step5tab").attr("src", "/images/newcustomerform/step5_step4.jpg");}
								  , function() {$("#step5tab").attr("src", "/images/newcustomerform/step5.jpg");}
								  );
		$("#step10btn1,#step10btn3").hover(   function(){$(this).attr("src", "/images/newcustomerform/right_button_orange_hover.png");}
											, function(){$(this).attr("src", "/images/newcustomerform/right_button_orange.png");}
											);
		$("#step10btn4block").hover(  function(){$("#step10btn4").attr("src", "/images/newcustomerform/right_button_orange_hover.png");}
									, function(){$("#step10btn4").attr("src", "/images/newcustomerform/right_button_orange.png");}
									);
		$("#newCustomerFormSubmitPrint").hover(  function() {$("#newCustomerFormSubmitPrint").attr("src", "/images/newcustomerform/print_hover.gif");}
											   , function() {$("#newCustomerFormSubmitPrint").attr("src", "/images/newcustomerform/print.gif");}
											   );
		$("#newCustomerFormSubmitSend").hover(   function() {$("#newCustomerFormSubmitSend").attr("src", "/images/newcustomerform/confirm_hover.gif");}
											   , function() {$("#newCustomerFormSubmitSend").attr("src", "/images/newcustomerform/confirm.gif");}
											   );
	}
	function initClicks()
	{
		$("#step1btn1").click(function(){
			if(validateStep1Mail()) {
				$.ajax({
					   type: "POST",
					   url: "/customerFormStep1Action.asp",
					   data: ({s1o1: $("#s1o1").val(), s1o2: $("#s1o2").val(), s1o3: $("#s1o3").val(), s1o4: $("#s1o4").val()}),
					   success: function(msg){
						   _gaq.push(['_trackPageview', '/mal/privat/pensionsspara/ansokan-hem']);
						   $("#step1orderform").html("<span class=\"underrubrik\">Skicka hem ansökan</span><br /><br />Tack!<br />Vi kommer att skicka hem<br />ansökan till dig.");
					   }
				});
			}
		});
		$("#step10btn1").click(function(){
			if(validateStep10Mail()) {
				$.ajax({
					   type: "POST",
					   url: "/customerFormStep1Action.asp",
					   data: ({s10o1: $("#s10o1").val(), s10o2: $("#s10o2").val(), s10o3: $("#s10o3").val(), s10o4: $("#s10o4").val()}),
					   success: function(msg){
						   _gaq.push(['_trackPageview', '/mal/privat/malspara/ansokan-hem']);
						   $("#step10orderform").html("<span class=\"underrubrik\">Skicka hem ansökan</span><br /><br />Tack!<br />Vi kommer att skicka hem<br />ansökan till dig.");
					   }
				});
			}
		});
		
		$("#step1btn3").click(function(){
			if(validateStep1Email()) {
				$.ajax({
					type: "POST",
					url: "customerFormStep1Action.asp",
					data: ({s1o5: $("#s1o5").val()}),
					success: function(msg){
						_gaq.push(['_trackPageview', '/mal/privat/pensionsspara/ansokan-melja']);
						$("#s1o5msg").html("<br /><span class=\"error\">Tack! Ansökan har skickats.</span>");
					}
				});
				
			}
		});
		$("#step10btn3").click(function(){
			if(validateStep10Email()) {
				$.ajax({
					type: "POST",
					url: "customerFormStep1Action.asp",
					data: ({s10o5: $("#s10o5").val()}),
					success: function(msg){
						_gaq.push(['_trackPageview', '/mal/privat/malspara/ansokan-melja']);
						$("#s10o5msg").html("<br /><span class=\"error\">Tack! Ansökan har skickats.</span>");
					}
				});
				
			}
		});
		$("#step1btn4block").click(function(){
											_gaq.push(['_trackPageview', '/mal/nedladdning/PP_Pension_ansokan_privat_pensionssparande.pdf']);
											window.open("/PP_Pension_ansokan_privat_pensionssparande.pdf");
											return false;
											});
		$("#step10btn4block").click(function(){
											_gaq.push(['_trackPageview', '/mal/nedladdning/PP_Pension_ansokan_Malsparande.pdf']);
											window.open("/PP_Pension_ansokan_Malsparande.pdf");
											return false;
											});
		$("#s2o2_No").click(function() {
			$("#s2o2_extend").fadeOut(500, step2);
		});
		$("#s2o2_Yes").click(function() {
			$("#s2o2_extend").fadeIn(500, step2);
		});
		$("#s3o2_No").click(function() {
			$("#s3o2_extend").fadeOut(500, step3);
		});
		$("#s3o2_Yes").click(function() {
			//parseXmlFunds();
			$("#s3o2_extend").fadeIn(500, step3);
		});
		$("#step1goto2, #step1goto2block").click(function() {
			_gaq.push(['_trackPageview', '/mal/privat/pensionsspara/ansokan-skarmen']);
			$("#step1").fadeOut(500);
			$("#step2").fadeIn(500);
			$.scrollTo("#step2", 10);
			//trackEvent("Forms", "Spara privat - Steg 1: Hur mycket vill du spara", "Hur mycket vill du spara");
		});
		$("#step1goto10, #step1goto10map").click(function() {
			window.location.href = "/borja_spara_nu_s310.html#malspara";
			applyForMalsparaState();
			
			$("#step1").fadeOut(500);
			$("#step10").fadeIn(500);
			$.scrollTo("#step10", 10);
			step10();
			//trackEvent("Forms", "Spara privat - Steg 1: Hur mycket vill du spara", "Hur mycket vill du spara");
		});
		$("#step2goto1").click(function() {
			$("#step2").fadeOut(500);
			$("#step1").fadeIn(500);
			$.scrollTo("#step1", 10);
			step1();
		});
		$("#step2goto3, #step2goto3map").click(function() {
			if(validateStep2()) {
				//$.scrollTo("#step3", 200);
				$("#step2").fadeOut(500);
				$("#step3").fadeIn(500);
				$.scrollTo("#step3", 10);
				trackEvent("Forms", "Spara privat - Steg 2: Välj fonder", "Välj fonder");
				step3();
			}
		});
		$("#step3goto2, #step3goto2map").click(function() {
			if(validateStep3()) {
				$("#step3").fadeOut(500);
				$("#step2").fadeIn(500);
				$.scrollTo("#step2", 10);
				step2();
			}
		});
		$("#step3goto4, #step3goto4map").click(function() {
			if(validateStep3()) {
				$("#step3").fadeOut(500);
				$("#step4").fadeIn(500);
				$.scrollTo("#step4", 10);
				trackEvent("Forms", "Spara privat - Steg 3: Dina uppgifter", "Dina uppgifter");
				step4();
			}
		});
		$("#step4goto3, #step4goto3map").click(function() {
			$("#step4").fadeOut(500);
			$("#step3").fadeIn(500);
			$.scrollTo("#step3", 10);
			step3();
		});
		$("#step4goto5, #step4goto5map").click(function() {
			if(validateStep4()) {
				$("#step4").fadeOut(500);
				$("#step5").fadeIn(500);
				$.scrollTo("#step5", 10);
				trackEvent("Forms", "Spara privat - Steg 4: Bekräfta ansökan", "Bekräfta ansökan");
				step5();
			}
		});
		$("#step5goto4, #step5goto4map").click(function() {
			$("#step5").fadeOut(500);
			$("#step4").fadeIn(500);
			$.scrollTo("#step4", 10);
			step4();
		});
		$("#step10goto1, #step10goto1map").click(function() {
			window.location.href = "/borja_spara_nu_s310.html#pensionsspara";
			applyForOriginalState();
			
			$("#step10").fadeOut(500);
			$("#step1").fadeIn(500);
			$.scrollTo("#step1", 10);
			step1();
			//trackEvent("Forms", "Spara privat - Steg 1: Hur mycket vill du spara", "Hur mycket vill du spara");
		});
		$("#newCustomerFormSubmitPrint").click(function() {
			if(validateStep5()) //if($("#s5o1:checked").val() != null)
			{
				$("#step5").fadeOut(500);
				$("#step6a").fadeIn(500);
				$.scrollTo("#step6a", 10);
				trackEvent("Forms", "Spara privat - Steg 5: Tack - Skriv ut", "Ansökan skrivs ut");
				trackFacebook();
				//alert("Submit for print");
				_gaq.push(['_trackPageView', '/mal/privat/pensionsspara/ansokan-skarmen-skrivut']);
				$("#newCustomerForm").submit();
			}
			else
			{
				alert('Du måste klicka i \n"Jag har tagit del av förköpsinformation och avtalsvillkor"\n för att fortsätta.');
			}
		});
		$("#newCustomerFormSubmitSend").click(function() {
			if(validateStep5()) //if($("#s5o1:checked").val() != null)
			{
				$("#step5").fadeOut(500);
				$("#step6b").fadeIn(500);
				$.scrollTo("#step6a", 10);
				$("#newCustomerForm").attr("target", "newCustomerFormSendTarget");
				//alert($("#newCustomerForm").attr("target"));
				$("#sendDontPrint").val(1);
				//trackEvent("Forms", "Spara privat - Steg 5: Tack - Ansökan", "Ansökan har skickats in");
				//trackFacebook();
				_gaq.push(['_trackPageView', '/mal/privat/pensionsspara/ansokan-skarmen-skicka']);
				$("#newCustomerForm").submit();
			}
			else
			{
				alert('Du måste klicka i \n"Jag har tagit del av förköpsinformation och avtalsvillkor"\n för att fortsätta.');
			}
		});
	}
	
	function initHide()
	{
		$("#s2o2_extend").hide();
		$("#s3o2_extend").hide();
		
	}
	
	function initClueTips()
	{
		$("a.infotext").cluetip({
			hoverIntent: {
				sensitivity:  1,
				interval:     250,
				timeout:      750    
			}
			, cluetipClass: 'rounded'
			, dropShadow: false
			, local: true
			, width: 400
		});
	}
	
	function initValidators()
	{
		$("#newCustomerFormStep1").validate();
		$("#newCustomerFormStep10").validate();
		$("#newCustomerForm").validate();
		
		$.validator.addClassRules("percent", { range: [0, 100] });
		$.validator.addMethod("socialsecuritynumber", function(value, element) {
															   return this.optional(element) || checkPnr(value);
															   }, "Ange ett korrekt personnummer<br />");
	}
	
	function validateStep1Mail() {
		var r = true;
		r = r && $("#s1o1").valid();
		r = r && $("#s1o2").valid();
		r = r && $("#s1o3").valid();
		r = r && $("#s1o4").valid();
		return r;
	}
	function validateStep10Mail() {
		var r = true;
		r = r && $("#s10o1").valid();
		r = r && $("#s10o2").valid();
		r = r && $("#s10o3").valid();
		r = r && $("#s10o4").valid();
		return r;
	}
	function validateStep1Email() {
		var r = false;
		if($("#s1o5").val().length > 0) {
			r = $("#s1o5").valid();
		}
		return r;
	}
	function validateStep10Email() {
		var r = false;
		if($("#s10o5").val().length > 0) {
			r = $("#s10o5").valid();
		}
		return r;
	}
	
	function step1() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step1").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function step10() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step10").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function step2() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step2").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function step3() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step3").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function step4() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step4").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function step5() {
		$("#divNewCustomerForm").height(Math.max($("#divNewCustomerForm").outerHeight(), $("#step5").outerHeight() + 20));
		newCustomerFormAdjustHeights();
	}
	function newCustomerFormAdjustHeights() {
		$("#centerColumn").height(Math.max($("#centerColumn").outerHeight(), $("#divNewCustomerForm").outerHeight()));
		setColumnHeights();
	}
	function setColumnHeights()
	{
		var l = $("#leftColumn");
		var c = $("#centerColumn");
		var r = $("#rightColumn");
		var h = Math.max(
			l.outerHeight(),
			Math.max(
				c.outerHeight(),
				r.outerHeight()
			)
		);
		l.height(h - (l.outerHeight() - l.innerHeight()));
		c.height(h - (c.outerHeight() - c.innerHeight()));
		r.height(h - (r.outerHeight() - r.innerHeight()));
	}
	
	function validateStep2() {
		var r = true;
		if(r && $("#s2o1optional").val().length > 0) {
			r = $("#s2o1optional").valid();
		}
		return r;
	}
	function validateStep3() {
		return true;
	}
	function validateStep4() {
		var r = true;
		if(r && $("#s4o7").val().length > 0) {
			r = $("#s4o7").valid();
		}
		if(r && $("#s4o3").val().length > 0) {
			r = $("#s4o3").valid();
		}
		return r;
	}
	function validateStep5() {
		var r = true;
		r = $("#s5o1").valid();
		return r; //$("#s5o1:checked").val() != null;
	}
	function checkPnr(strPnr) {
		var bool1 = false;
		// kontrollerar att 10 heltal matats in
		bool1 = strPnr.match(/^\d{10}$/); 
		if( !bool1 ) {
			// kontrollerar att 6 och 4 heltal matats in
			bool1 = strPnr.match(/^\d{6}-\d{4}$/);
			if( bool1 ) {
				strPnr = strPnr.replace(/^(\d{6})-(\d{4})$/, "$1$2");
			}
		}
		if( !bool1 ) {
			//alert("checkPnr felaktig sträng: " + strPnr)
			return(false);
		} else {
			// Godkänner ett giltigt personnummer
			bool1 = strPnr.match(/^\d{2,2}[01]{1,1}\d{1,1}[0123]{1,1}\d{1,1}\d{4,4}$/);
			if( !bool1 ) {
				//alert("checkPnr ej godkänt datum: " + strPnr)
				return(false);
			} else {
				// variabler för kontroll av slutsiffra 
				var siffra=0;           // varje delsiffra i pnr 
				var ental=0;            // entalet (när siffra större än 9) 
				var kNummer=0;          // den siffra som SKALL vara sist i pnr 
				var summa=0;            // summan av samtliga siffror 
				var testSumma=0;        // för att plocka ut tiotalet ur summan 
				var i=0;                // loop för utplockning av varje delsiffra i pnr 
				var tiotal=0;           // loop för att leta antalet tiotal 
				
				// STEG 1 kontrollerar och summerar siffra för siffra i pnr 
				for(i=0; i<9; i++) { 
					siffra=parseInt(strPnr.charAt(i)); 
					// multiplicerar utvald Siffra med 2 varannan gång 
					if (i%2 == 0) { 
						siffra = siffra * 2; 
					} 
					// om den nyligen multiplicerade siffran är ett ENTAL 
					if (siffra < 10) { 
						summa += siffra; 
					} else { 
						// om den nyligen multiplicerade siffran är ett TIOTAL 
						ental = siffra - 10; 
						summa = summa + 1 + ental; 
					} 
				}
					
				// STEG 2, räknar ut kontroll-siffran 
				testSumma=summa; 
				while( testSumma > 9 ) { 
					testSumma-=10;
					tiotal++; 
				} 
				tiotal++;                 // ökar på till närmast högre 
				tiotal = tiotal * 10;     // ger det fullständiga tiotalet 
				kNummer = tiotal - summa; // kontrollsiffran blir närmast högre tiotal - summan 
		
				// om kontrollSiffran är ett tiotal är ju andra siffran entalet, (dvs alltid 0) 
				if (kNummer % 10 == 0) { 
					kNummer=0;
				}
				if (kNummer == parseInt(strPnr.charAt(9))) {
					//alert("checkPnr godkänd: " + strPnr)
					return(true);
				} else {
					//alert("checkPnr ej godkänd kontrollsiffra: " + strPnr)
					return(false);
				}
			}
		}
	}
	
	function showFund(cid) {
		var u = "http://cust.msse.se/SE/pppension/funds/overview.asp?cid=" + cid +"&amp;lang=SV&amp;curiso=SEK&amp;country=SE&amp;lastpage=Sök fond&amp;LastPageURL=/SE/pppension/quickrank/index.asp?tab=HSTRY|lang=SV|univ=SE1|country=SE|curiso=SEK|mec=|cat=-1|search=|sortby=Custom_11|sortorder=ASC|PageNo=1|Firstletter=";
		mywindow=window.open(u,'info','width=556,height=600,resizable=yes,scrollbars=yes,menubar=no,toolbar=no,directories=no,location=no,status=no');
		mywindow.moveTo(140,150);
	}
	function loadFunds()
	{
		$.get("/morningstar_funds.xml", function(xml){
			var preamble = ""
				+ "Välj fonder i listan och ange hur stor del av ditt sparande du vill spara i varje fond. Summan ska vara 100 procent. "
				+ "I detta formulär kan du välja maximalt 5 fonder. När din ansökan är registrerad kan du välja upp till 10 fonder på vårt Internetkontor.<br /><br />"
			var table = ""
				+ "<table id=\"s3o2_funds\" cellspacing=\"0\" cellpadding=\"0\">\n"
				+ "<tr><th>Fondnamn<\/th><th class=\"right\">Ange procent<\/th><\/tr>"
			;
			// <th>iår%<\/th><th>1år%<\/th><th>3år%<\/th><th>5år%<\/th><th>10år%<\/th>
			var i = 0;
			$(xml).find("item").each(function() {
				table += ""
					+ "<tr><td class=\"left\">"
					+ "<a href=\"http://cust.msse.se/SE/pppension/pdf/PPPension.aspx?cid=" + $(this).find("cid").text() + "\" title=\"" + $(this).find("title").text() + "\" target=\"_blank\">"
					+ "<img src=\"/images/pdf.gif\" alt=\"\" border=\"0\" />"
					+ "<\/a> "
					//+ "<a id='" + $(this).find("cid").text() + "' href=\"javascript:$ncf.showFund('" + $(this).find("cid").text() + "');\" title=\"" + $(this).find("title").text() + "\">"
					+ "<a class=\"fundItem\" id=\"fund" + $(this).find("cid").text() + "\" href=\"javascript:void(0);\" title=\"" + $(this).find("title").text() + "\">"
					+ $(this).find("title").text()
					+ "<\/a>"
					+ "<\/td>\n"
					+ "<td><inp" + "ut type=\"text\" maxlength=\"3\" class=\"w20 percent\" name=\"s3o3_" + i + "\" id=\"s3o3_" + i + "\" /><\/td>\n"
					+ "<\/tr>\n"
				;
	/*
					+ "<td>" + $(this).find("fc_YTD").text() + "<\/td>\n"
					+ "<td>" + $(this).find("fc_1_Year").text() + "<\/td>\n"
					+ "<td>" + $(this).find("fc_3_Year").text() + "<\/td>\n"
					+ "<td>" + $(this).find("fc_5_Year").text() + "<\/td>\n"
					+ "<td>" + $(this).find("fc_10_Year").text() + "<\/td>\n"
	*/
				i++;
			});
			table += "<\/table>";
			$("#s3o2_extend").html(preamble + table);
			$("#s3o2_extend tr:odd").each(function(){
				$(this).css("background-color", "#ebf5df");
			});
			$("#s3o2_extend a.fundItem").each(function(){
													   $(this).click(function(){
													   var id = this.id.replace("fund", "");
														showFund(id);
													   });
													   });
		});
	}
	
	function trackFacebook()
	{
		try {
			FB.trackConversion({
				'id' : 6002463646126,
				'h' : '0f03d38995',
				'value' : 10 // du kan ändra detta dynamiskt
			});
		} catch (e) {}
	}


	return {
		init : function()
		{
			initAll();
		}
	}
} (jQuery);

