﻿/**
 *
 * Handelsbanken Capital Markets HCM3.0
 * Master JavaScript behaviours
 * © 2010
 *
 * @depends jquery-1.3.2.min.js
 * @depends functions.js
 * @depends joose.min.js
 * @depends plugins/jquery.plugins.min.js
 */

jQuery.noConflict();

jQuery(document).ready(function(jQuery){

	var cosmetic = new application.Cosmetics;
	cosmetic.init();
	
	var cookie = new application.Cookies;
	cookie.init();
	
	var module = new application.Modules;
	module.latestQuestions();
	module.questionOfTheWeek();
	module.toolbar();
	module.priceTag();
	module.reportComment();
	//module.blogShare();
	module.askQuestion();
	module.slideShow();
	module.pageIntro();
	module.accordion();
	module.questionList();
	module.showHideIndex();
	module.tableSorter();
	
	var briefcase = new application.Briefcase;
	briefcase.createSliders();
	briefcase.init();
	briefcase.showHideInfo();
	briefcase.showHideForms();
	briefcase.preDefined();
	
	var form = new application.Forms;
	form.init();
	form.rules();
	form.validate();
	form.labelify();
		
});

Module('application', function (m) {

	Class('Cosmetics', {
		methods: {
			init: function(){
				
				/* TAB INDEX */
   				/*jQuery('.head').attr('tabindex', '1');
   				jQuery('.content').attr('tabindex', '2');
    			jQuery('.content .left').attr('tabindex', '3');
			    jQuery('.content .right').attr('tabindex', '4');
			    jQuery('.content .briefcase').attr('tabindex', '5');
			    jQuery('.content .actualities').attr('tabindex', '6');*/
				
				/* ADD OS AND BROWSER SPECIFIC CLASS TO BODY */
				var os      = jQuery.client.os.toLowerCase();
				var browser = jQuery.client.browser.toLowerCase();
				var version = 'v' + jQuery.client.version.toString().replace('.', '-');
				jQuery('body').addClass(os + ' ' + browser + ' ' + version + ' js-active');
				
				/* BLUR ALL LINKS AND BUTTONS */
				jQuery('a, input[type="submit"], input[type="button"]').bind('click, focus', function() { 
    				jQuery(this).blur(); 
				});
				
				/* ADD "LAST"-CLASS TO SOME OF THE ELEMENTS */
				jQuery('ol, ul:not(.latest-posts ul, .index.list ul), .latest-posts ul:last, table, .product-intro p').each( function(){
					jQuery(this).find('li:last, tr:last, td:last, p:last').addClass('last');
				});
				
				/* QUESTION OF THE WEEK */
				jQuery('.question-of-the-week fieldset:first label:last').addClass('last');
				
				/* ADD "HOVER"-CLASS TO ALL BUTTONS */
				jQuery('.button').live('mouseover', function(){
					jQuery(this).addClass('hover');
				}).live('mouseout' , function(){
					jQuery(this).removeClass('hover');
				});
								
				/* MAKE LINKS WITH "EXTERNAL"-CLASS OPEN I NEW WINDOW */
				jQuery('a.external, a[rel="external"]').attr('target', '_blank');
				
				/* STRIPE BRIEFCASES */
				jQuery('.briefcase').each( function(){
					jQuery(this).find('ul li:odd').addClass('odd');
				});
				
				/* PRODUCT INTRO */
				jQuery('.product-intro h2').each( function(){
					var link = jQuery(this).find('a').attr('href');
					jQuery(this).css('cursor', 'pointer').bind('click', function(){
						window.location = link;
						return false;
					});
				});
				
				/* RELATED CONTENT */
				jQuery('.related-content').each( function(){
					jQuery(this).find('ul:last').addClass('last');
				});
				
				/* POPUP NEW WINDOW */
				jQuery('.link-popup').popupWindow();
				
				/* POPUP 1024x768 */
				jQuery('.link-popup-large').popupWindow({
					width: 903,
					height: 649					
				});
				
				/* POPUP EXT GRAPH */
				jQuery('.link-popup-ext-graph').popupWindow({
					width: 990,
					height: 820					
				});
				
				/* BLOG HEADER */
				jQuery('.head-blog').bind('click', function(){
					window.location = jQuery(this).find('h1 a').attr('href');
					return false;
				});
				
				/* INDEX PAGE INTRO */
				jQuery('.index:not(".index.page") .page-intro:last').addClass('last');
				
				/* INDEX TABLE */
				jQuery('.module.index.table table').each(function(){
					jQuery(this).find('tr:odd').addClass('odd');
					jQuery(this).find('tr:even').addClass('even');
				});
				
				/* EDITOR TABLE */
				jQuery('.editorTable').find('tr:first').addClass('editorHeader');
				jQuery('.editorTable').each(function(){
					jQuery(this).find('tr:odd').addClass('odd');
					jQuery(this).find('tr:even').addClass('even');
				});
				
				/* ANNOTATED TIMELINE FIX */
				jQuery('.annotatedtimelinetable tbody tr td:gt(0)').hide();
				
				/* OLD BLOG BRIEFCASE */
				jQuery('.briefcase-blog').each( function(){
					jQuery(this).find('h4 a, .blog-info a').bind('click', function(){
						jQuery(this).parent().parent().find('.blog-info').toggle();;
						return false;
					});
				});
				
				jQuery('.blog').find('p img').each( function(){
					if (jQuery(this).attr('align') == 'right') {
						jQuery(this).addClass('right');
					}
				});
		
			}
		}
	});
	
	Class('Modules', {
		methods: {
			
			/* SLIDESHOW */
			slideShow: function() {
				
				jQuery('#slideshow ul').cycle({
					fx: 'fade', 
					speed: 1000, 
					timeout: 10000,
					pause: 1,
					pager: '#slideshow-navigation .navi .links'
				});

				jQuery('#play-pause').toggle( function(){
					jQuery('#slideshow ul').cycle('pause'); 
					jQuery(this).addClass('pause');
				}, function(){
					jQuery('#slideshow ul').cycle('resume', true); 
					jQuery(this).removeClass('pause');
				});
			
			},
			
			/* LATEST QUESTIONS */
			latestQuestions: function() {
				
				var latestQuestions = jQuery('#latest-questions ul:first');
				var countQuestions  = latestQuestions.find('li').length;
				
				if (countQuestions > 5) {
					
					countQuestions = countQuestions - 5;
					
					latestQuestions.find('li:gt(4)').hide().addClass('show-hide');
					latestQuestions.append('<p class="show-more-questions"><a href="#" id="show-more-questions" class="link-arrow-down">Visa fler frågor (' + countQuestions + ' st)</a></p>');
				
					jQuery('#show-more-questions').toggle( function(){
						latestQuestions.find('.show-hide').slideDown('fast', function(){
							jQuery('#show-more-questions').html('Visa färre frågor').removeClass('link-arrow-down').addClass('link-arrow-up');
						});
						return false;
					}, function(){
						latestQuestions.find('.show-hide').slideUp('fast', function(){
							jQuery('#show-more-questions').html('Visa fler frågor (' + countQuestions + ' st)').removeClass('link-arrow-up').addClass('link-arrow-down');
						});
						return false;
					});
					
				}
								
			},
			
			/* PAGE INTRO */ 
			pageIntro: function() {
				
				jQuery('.module.flash.hide').hide();
				jQuery('.page-intro .show-flash-movie').bind('click', function(){
					jQuery('#flash-movie').slideToggle('fast');
					return false;
				});
				
			},
			
			/* QUESTION OF THE WEEK MODULE */
			questionOfTheWeek: function() {
				
				var qotwObject = jQuery('#question-of-the-week:not(.old)');
				var qotwForm   = qotwObject.find('#form-question-of-the-week');
				var qotwResult = qotwObject.find('#question-of-the-week-result');
				var id         = jQuery('#question-id').val();
				
				qotwForm.css({'display':'block','float':'left'}).show();
				qotwResult.css({'display':'block','float':'left'}).hide();	
								
				if (jQuery.cookie('qestion-of-the-week-' + id) == 'true') {
					qotwForm.hide();
					qotwObject.find('h4 a').hide();
					qotwResult.show();
				} else {
					qotwObject.find('h4 a').toggle( function(){
						jQuery(this).html('Dölj resultat');
						qotwResult.show();
						qotwForm.hide();
						/*qotwResult.slideDown('fast', function(){
							qotwForm.slideUp('fast');
						});*/
						return false;
					}, function(){
						jQuery(this).html('Visa resultat');
						qotwResult.hide();
						qotwForm.show();					
						/*qotwForm.slideDown('fast', function(){
							qotwResult.slideUp('fast');
						});*/
						return false;
					});
				}
							
			},
			
			/* TOOLBAR MODULE */
			toolbar: function() {
								
				if (jQuery('body').hasClass('no')) {
					var printLinkTxt = 'Skriv ut sidan';
					var shareLinkTxt = 'Dela med dig';
					var shareTxt     = 'Dela på';
					var addTxt       = 'Lägg till på';
				} else if (jQuery('body').hasClass('fi')) {
					var printLinkTxt = 'Skriv ut sidan';
					var shareLinkTxt = 'Dela med dig';
					var shareTxt     = 'Dela på';
					var addTxt       = 'Lägg till på';
				} else {
					var printLinkTxt = 'Skriv ut sidan';
					var shareLinkTxt = 'Dela med dig';
					var shareTxt     = 'Dela på';
					var addTxt       = 'Lägg till på';
				}	
			
				// ADD PRINT BUTTON
				jQuery('.toolbar:not(ul.briefcase .toolbar)').find('ul.menu').prepend('<li><a href="#" class="link-print">' + printLinkTxt + '</a></li>');
				
				// ADD SHARE BUTTON
				jQuery('.toolbar:not(ul.briefcase .toolbar)').find('ul.menu').append('<li><a href="#" class="link-share">' + shareLinkTxt + '</a></li>');
				
				// ADD SHARE BUTTON
				jQuery('ul.briefcase .toolbar').find('ul.menu li:first').after('<li><a href="#" class="link-share">' + shareLinkTxt + '</a></li>');
								
				// ADD SHARE LINKS
				var url   = encodeURIComponent(window.location.href);
				var title = encodeURIComponent(jQuery('title').text());
				
				jQuery('.toolbar').append('<div class="share">' +
					'<ul>' +
						'<li><a href="http://www.facebook.com/share.php?u=' + url + '&t=' + title + '" title="' + shareTxt + ' Facebook" class="share-facebook">Facebook</a></li>' +
						'<li><a href="https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=' + url + '&title=' + title + '&top=1" title="Dela på Live" class="share-live">Live</a></li>' +
						'<li><a href="http://www.pusha.se/posta?url=' + url + '&title=' + title + '" title="' + shareTxt +' Pusha" class="share-pusha">Pusha</a></li>' +
						'<li><a href="http://delicious.com/save?url=' + url + '&title=' + title + '" title="' + addTxt + ' Del.icio.us" class="share-delicious">Del.icio.us</a></li>' +
						'<li><a href="http://twitter.com/home?status=' + url + '" title="' + shareTxt + ' Twitter" class="share-twitter">Twitter</a></li>' +
						'<li><a href="http://bookmarks.yahoo.com/toolbar/savebm?u=' + url + '&t=' + title + '" title="' + shareTxt + ' Yahoo" class="share-yahoo">Yahoo</a></li>' +
						'<li><a href="http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=' + url + '&title=' + title + '" title="' + shareTxt + ' Google" class="share-google">Google</a></li>' +
					'</ul>' +
				'</div>');
				
				// PRINT PAGE
				jQuery('.link-print').live('click', function(){
					window.print();
					return false;
				});
				
				// INIT
				jQuery('.tip-a-friend, .share').hide();
				jQuery('.toolbar li').removeClass('active');
				
				// TIP A FRIEND
				jQuery('.link-tip').bind('click', function(){
					jQuery(this).parent().parent().find('.link-share').parent().removeClass('selected');
					jQuery(this).parent().toggleClass('selected');
					jQuery(this).parent().parent().parent().find('.share').slideUp('fast', function(){
						jQuery(this).parent().find('.tip-a-friend').slideToggle('fast');
					});
					return false;
				});
											
				// SHARE PAGE
				jQuery('.link-share').bind('click', function(){
					jQuery(this).parent().parent().find('.link-tip').parent().removeClass('selected');
					jQuery(this).parent().toggleClass('selected');
					jQuery(this).parent().parent().parent().find('.tip-a-friend').slideUp('fast', function(){
						jQuery(this).parent().find('.share').slideToggle('fast');
					});
					return false;
				});
			
			},
			
			/* PRICE TAG MODULE */
			priceTag: function () {
				
				/* DISPLAY MODAL WINDOW IF BRIEFCASE HAS ITEMS */
				jQuery('.price-tag select').bind('change', function(){
					if ( jQuery(this).val() == 0 ) {
						jQuery('#more-offer').modal({
							closeClass: 'close-modal',
							maxWidth: 350
						});
					}
				});
													
				/* ASIGN ACTIONS TO FORM FIELDS */
				jQuery('.price-tag input[type="submit"]').bind('click', function(){
					var product        = jQuery(this).metadata().offerId;
					var cartItem       = jQuery('#offer-' + product);
					var tempNoProducts = parseInt( jQuery('#offer-' + product).val() );
					var noProducts     = tempNoProducts + parseInt( jQuery('#amount-to-cart-' + product).val() );
					var briefcase      = new application.Briefcase;
					var css            = 'ui-effects-transfer';
					var effect         = 'transfer';
					var speed          = 600;
					jQuery(this).parent().parent().parent().parent().effect( effect, {to:cartItem.parent(), className:css}, speed, callback );
					function callback() {
						cartItem.val(noProducts);
						briefcase.updateCart(cartItem);
					}
					return false;
				});
				
			},
						
			tableSorter: function() {
				
				jQuery('.table-sorter').tablesorter({
					sortList: [[0,0]],
					headers: {
						1: {
							sorter: false
						}
					},
					widgets: ['zebra']
				});              
			
			},
			
			showHideIndex: function() {
				
				jQuery('.show-hide-index').each( function(){
					
					var show    = parseInt(jQuery(this).metadata().show);
					var element = jQuery(this).metadata().element;
					var text    = jQuery(this).metadata().text;
					
					if (element == 'table') {
						
						var indexTable = jQuery(this).find('table:first');
						var countIndex = indexTable.find('tr').length;
						var show = show - 1;
							
						if (countIndex > show) {
							
							countIndex = countIndex - (show + 1);
							
							indexTable.find('tr:gt(' + show + ')').hide().addClass('show-hide');
							indexTable.append('<tr class="show-more-link"><td colspan="2"><p class="show-more-index"><a href="#" id="show-more-index-table" class="link-arrow-down">Visa fler ' + text + ' (' + countIndex + ' st)</a></p></td></tr>');
							
							jQuery('#show-more-index-table').toggle( function(){
								indexTable.find('.show-hide').slideDown('fast', function(){
									jQuery('#show-more-index-table').html('Visa färre ' + text).removeClass('link-arrow-down').addClass('link-arrow-up');
								});
								return false;
							}, function(){
								indexTable.find('.show-hide').slideUp('fast', function(){
									jQuery('#show-more-index-table').html('Visa fler  ' + text + ' (' + countIndex + ' st)').removeClass('link-arrow-up').addClass('link-arrow-down');
								});
								return false;
							});
							
						}
						
					} else if (element == 'list') {
																		
						var indexList  = jQuery(this).find('ul:first');
						var countIndex = indexList.find('li').length;
						var showTemp   = show + 1;
					
						if (countIndex > showTemp) {
							
							countIndex = countIndex - showTemp;
						
							indexList.find('li:gt(' + show + ')').hide().addClass('show-hide').wrap('<div class="show-hide"></div>');
							indexList.append('<br class="clear"/><p class="show-more-index"><a href="#" id="show-more-index-list" class="link-arrow-down">Visa fler ' + text + ' (' + countIndex + ' st)</a></p>');
						
							jQuery('#show-more-index-list').toggle( function(){
								indexList.find('.show-hide').slideDown('fast', function(){
									jQuery('#show-more-index-list').html('Visa färre index').removeClass('link-arrow-down').addClass('link-arrow-up');
								});
								return false;
							}, function(){
								indexList.find('.show-hide').slideUp('fast', function(){
									jQuery('#show-more-index-list').html('Visa fler index (' + countIndex + ' st)').removeClass('link-arrow-up').addClass('link-arrow-down');
								});
								return false;
							});
							
						}
						
					}
				
				});
				
				/*jQuery('.index.list').each( function(){
													
					var indexList  = jQuery(this).find('ul:first');
					var countIndex = indexList.find('li').length;
									
					if (countIndex > 6) {
						
						countIndex = countIndex - 6;
					
						indexList.find('li:gt(5)').hide().addClass('show-hide');
						indexList.append('<br class="clear"/><p class="show-more-index"><a href="#" id="show-more-index" class="link-arrow-down">Visa fler index (' + countIndex + ' st)</a></p>');
					
						jQuery('#show-more-index').toggle( function(){
							indexList.find('.show-hide').slideDown('fast', function(){
								jQuery('#show-more-index').html('Visa färre index').removeClass('link-arrow-down').addClass('link-arrow-up');
							});
							return false;
						}, function(){
							indexList.find('.show-hide').slideUp('fast', function(){
								jQuery('#show-more-index').html('Visa fler index (' + countIndex + ' st)').removeClass('link-arrow-up').addClass('link-arrow-down');
							});
							return false;
						});
						
					}
								
				});*/
				
			},
			
			/* REPORT COMMENT */
			reportComment: function() {
		
				jQuery('.report-comment').bind('click', function(){
					jQuery('#report-comment').modal({
						closeClass: 'close-modal',
						maxWidth: 350,
						minHeight: 330
					});
					return false;
				});
				
			},
			
			/* ASK A QUESTION */
			askQuestion: function() {
				
				jQuery('#ask-a-question input[type="checkbox"]').bind('click', function(){
					(jQuery('#ask-a-question input[type="checkbox"]').is(':checked') == true) ? jQuery('#accept-container').slideDown('fast') : jQuery('#accept-container').slideUp('fast');
				});

			},
			
			/* SHARE THIS ON BLOG */
			blogShare: function() {
							
				jQuery('.list-blog p.author').each( function(){
					jQuery(this).append('<a href="#" class="link-share" title="Dela denna bloggpost">Dela</a>');
				});
				
				jQuery('body').append('<div class="tooltip-container share" id="tooltip-share">' + 
					'<ul>' +
						'<li><a href="http://www.facebook.com/share.php?u=[url]&t=[title]" class="share-facebook" title="Dela på Facebook">Facebook</a></li>' +
						'<li><a href="https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=[url]&title=[title]&top=1" class="share-live" title="Dela på Live">Live</a></li>' +
						'<li><a href="http://www.pusha.se/posta?url=[url]&title=[title]" class="share-pusha" title="Dela på Pusha">Pusha</a></li>' +
						'<li><a href="http://delicious.com/save?url=[url]&title=[title]" class="share-delicious" title="Dela på Del.icio.us">Del.icio.us</a></li>' +
						'<li><a href="http://twitter.com/home?status=[url]" class="share-twitter" title="Dela på Twitter">Twitter</a></li>' +
						'<li><a href="#" class="share-yahoo" title="Dela på Yahoo">Yahoo</a></li>' +
						'<li><a href="http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=[url]&title=[title]" class="share-google" title="Dela på Google">Google</a></li>' +
					'</ul>' +
				'</div>');
							 
				jQuery('.link-share:not(.toolbar .link-share)').bind('click', function(e) {
					
					var url   = encodeURIComponent(jQuery(this).parent().parent().find('h2 a, h3 a').attr('href'));
					var title = encodeURIComponent(jQuery(this).parent().parent().find('h2 a, h3 a').text());
					
					jQuery('#tooltip-share li').each( function(){
						var link = jQuery(this).find('a').attr('href');
						link = link.replace('[url]', url).replace('[title]', title);
						jQuery(this).find('a').attr('href', link);
					})
					
					var pos    = jQuery(this).position();
					var width  = jQuery(this).width();
					var left   = pos.left;
					var height = (jQuery(this).parent().parent().parent().find('.tooltip-container.share').height()) * -1;
					
					jQuery('body').find('.tooltip-container.share').css({
						top: (e.pageY - 180) + 'px',
						left: (e.pageX - 30) + 'px'
					}).toggle();
					
					return false;
					
				});
				
			},
			
			accordion: function() {
				
				jQuery('.accordion h3:odd').addClass('odd');
				jQuery('.accordion').accordion({
					clearStyle: true
				});
			
			},
						
			questionList: function() {
				
				var questions = jQuery('#list-questions');
				
				//Find selected question
				var question = questions.find('.selectedQ').html();
				
				if (question != null)
				{
				    //Remove question from list and add at the top
				    questions.find('.selectedQ').remove();
				    questions.find('.qList').prepend('<li>' + question + '</li>');				    
				}
				
				questions.find('.hidden p:not(.meta)').hide();
				questions.find('h3').wrapInner('<a href="#"></a>').bind('click', function(){
					jQuery(this).parent().find('p:not(.meta)').slideToggle('fast');
					return false;
				})				
			}			
		}		
	});
	
	Class('Briefcase', {
		methods: {
			init: function (){
			
				var briefcase   = new m.Briefcase;
				var cookie      = new application.Cookies;
				var inputFields = jQuery('#briefcase #cart input[type="text"]');
				
				jQuery('#briefcase').find('h4').append(' <a href="#" title="Visa information" id="link-show-hide-info-briefcase"><img src="/images/icon-i.jpg" alt="i" /></a>');
				jQuery('#briefcase').find('#cart').prepend('<p class="info" id="briefcase-info"><span></span> <a href="#">Dölj info</a></p>');
				jQuery('#briefcase').find('#cart li').attr('sum','0');
				jQuery('#briefcase').find('#cart input[type="submit"]').after('<input type="button" value="Provräkna på portföljen" class="button calculate" id="calculate-button" />');
					
				/* CREATE CALCULATION CONTAINERS */
				jQuery('#briefcase #cart input[type="submit"]').before('<div class="calculate-sum" id="calculate">' +
					'<div class="container highlight" id="investment-sum">' +
						'<h5><a href="#" title="Töm portföljen" id="btn-reset-cart" class="btn-reset">Rensa</a> Du betalar inkl courtage</h5>' +
						'<p>0 kr</p>' +
					'</div>' +
					'<div class="container advanced-calculator" id="payback-sum">' +
						'<h5>Du får minst tillbaka</h5>' +
						'<p>0 kr</p>' +
					'</div>' +
					'<div class="container advanced-calculator" id="refund-sum">' +
						'<h5>Återbetalt belopp</h5>' +
						'<p>0 kr</p>' +
					'</div>' +
				'</div>');
				
				/* BOUNCE BUBBLE */
				if (jQuery.cookie('briefcase-bubble') != 'false'){
					jQuery('#briefcase').prepend('<div class="bubble black" id="briefcase-bubble">' +
						'<h5>Provplacera i portföljen</h5>' +
						'<p>Klicka på namnen för att läsa mer om respektive placering.</p>' +
					'</div>');
					setTimeout(bounceElement, 3000);
					cookie.edit('briefcase-bubble', 'false');
				}
				
				function bounceElement() {
					//briefcase.showHideCalculation('advanced');
					var time   = 300;
					var effect = 'swing';
					jQuery('.bubble').show().css('opacity', '0')
					.animate({top: '-=10px', 'opacity': '1'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px'}, time, effect)
					.animate({top: '-=10px'}, time, effect)
					.animate({top: '+=10px', 'opacity': '0'}, time, effect, hideAdvanced);
				}
				
				function hideAdvanced() {
					//briefcase.showHideCalculation('simple');
				}
							
				/* FORCE ENTER-KEY IN FORMFIELDS BEHAVE AS TABS */								
				(jQuery.browser.mozilla) ? inputFields.keypress(checkForEnter) : inputFields.keydown(checkForEnter);
				
				/* CHECK FOR ENTER KEY */
				function checkForEnter(event) {
					if (event.keyCode == 13) {
						
						currentBoxNumber = inputFields.index(this);
						inputFields[currentBoxNumber].blur();
						
						if (inputFields[currentBoxNumber+1] != null) {
							nextBox = inputFields[currentBoxNumber+1];
							nextBox.focus();
							nextBox.select();
						}
						
						event.preventDefault();
						return false;
					
					}
				}
								
				/* ADD TO BRIEFCASE (JANNES PLACERINGSFÖRSLAG) */
				jQuery('.add-to-briefcase').bind('click', function(){
					
					var itemsArr   = jQuery(this).metadata().items.split(',');
					var offerId    = jQuery('#offers-id').val();
					var cookieName = 'briefcase-items-' + offerId;
					var tempArr    = jQuery.cookie(cookieName).split(',');
					var itemsStr   = itemsArr.join(',');
					var tempStr    = tempArr.join(',');
					var tempItems  = 0;
					
					jQuery('#briefcase #cart input[type="text"]').each( function(){
						tempItems = tempItems + parseInt(jQuery(this).val());
					});
					
					if (tempItems == 0) {
						jQuery('#briefcase #cart input[type="text"]').each( function(index){
							if (jQuery(this).val() != itemsArr[index]){
								jQuery(this).val(itemsArr[index]);
								briefcase.showHideCalculation('advanced');
								briefcase.updateCart(jQuery(this));
							}
						});
						jQuery('html, body').animate({scrollTop:0}, 'fast');				
					} else if (itemsStr != tempStr) {
						jQuery('#cart-replace').modal({
							closeClass: 'close-modal',
							maxWidth: 350,
							onShow: function (dialog) {
								jQuery('#cart-replace input[type="button"]').bind('click', function(){
									jQuery('#briefcase #cart input[type="text"]').each( function(index){
										if (jQuery(this).val() != itemsArr[index]){
											jQuery(this).val(itemsArr[index]);
											briefcase.showHideCalculation('advanced');
											briefcase.updateCart(jQuery(this));
										}
									});
									jQuery.modal.close();
									jQuery('html, body').animate({scrollTop:0}, 'fast');				
								});
							}
						});
					}  			
					return false;
				});
																
				/* ASIGN ACTIONS TO FORM FIELDS */
				jQuery('#briefcase #cart input[type="text"]').each( function(index){
					jQuery(this).bind('change', function(){
						var offerId    = jQuery('#offers-id').val();
						var cookieName = 'briefcase-items-' + offerId;
						var itemArr    = jQuery.cookie(cookieName).split(',');
						(/^\.?jQuery/.test(jQuery(this).val()) || !/^-?\d*\.?\d*$/.test(jQuery(this).val())) ? jQuery(this).val(itemArr[index]) : briefcase.updateCart(jQuery(this));
					});
				});
							
				(jQuery.cookie('briefcase-state') != null) ? briefcase.showHideCalculation(jQuery.cookie('briefcase-state')) : briefcase.showHideCalculation('simple');
				
				/* IF QUERYSTRING NOT NULL */
				var offerId    = jQuery('#offers-id').val();
				var cookieName = 'briefcase-items-' + offerId;
				
				if (jQuery.jqURL.get('portfolj') != null && jQuery.cookie(cookieName) != null) {
										
					/* GET ITEMS IN CART GENERATED BY SERVER */
					var itemsArr = new Array();
					jQuery('#briefcase #cart input[type="text"]').each( function(index){						
						itemsArr.push(jQuery(this).val());
					});
					
					var activeItems = itemsArr.toString();
					var offerId     = jQuery('#offers-id').val();
					var cookieName  = 'briefcase-items-' + offerId;
					var cookieItems = jQuery.cookie(cookieName).toString();
					
					if (activeItems != cookieItems){
						jQuery('#cart-replace').modal({
							closeClass: 'close-modal',
							maxWidth: 350,
							onShow: function (dialog) {
								jQuery('#cart-replace input[type="button"]').bind('click', function(){
									jQuery('#briefcase #cart input[type="text"]').each( function(index){
										if (jQuery(this).val() != itemsArr[index]){
											jQuery(this).val(itemsArr[index]);
											briefcase.updateCart(jQuery(this));
										} else{
											briefcase.calculateOfferSum(jQuery(this));
											briefcase.calculateTotalOfferSum();
											briefcase.calculateProfit();
										}
									});
									jQuery.modal.close();
								});
							}
						});
						
					} else {
						
						jQuery('#briefcase #cart input[type="text"]').each( function(index){
							if (jQuery(this).val() != itemsArr[index]){
								jQuery(this).val(itemsArr[index]);
								briefcase.updateCart(jQuery(this));
							} else{
								briefcase.calculateOfferSum(jQuery(this));
								briefcase.calculateTotalOfferSum();
								briefcase.calculateProfit();
							}
						});

					}
									
				} else {
					
					var offerId    = jQuery('#offers-id').val();
					var cookieName = 'briefcase-items-' + offerId;
					
					if (jQuery.cookie(cookieName) != null) {
						var itemsArr = jQuery.cookie(cookieName).split(',');
						jQuery('#briefcase #cart input[type="text"]').each( function(index){
							jQuery(this).val( itemsArr[index] );
							briefcase.calculateOfferSum(jQuery(this));
							briefcase.calculateTotalOfferSum();
							briefcase.calculateProfit();
						});
					}
				
				}
				
				/* SHOW HIDE ADVANCED MODE IN BRIEFCASE */
				jQuery('#calculate-button').bind('click', function(){
					(jQuery.cookie('briefcase-state') == 'simple') ? briefcase.showHideCalculation('advanced') : briefcase.showHideCalculation('simple');
				});	
								
				/* RESET BRIEFCASE */
				jQuery('#btn-reset-cart').bind('click', function(){
					briefcase.reset();
					return false;
				});
				
				/* SUBMIT BRIEFCASE */
				jQuery('#form-cart').submit( function(){
					var numberItems = 0;
					jQuery('#briefcase #cart input[type="text"]').each( function(index){
						numberItems = numberItems + parseInt(jQuery(this).val());
					});
					if (numberItems != 0) {
						MakeBuyLinks();
						CheckSelected();
						
						//ADMETA PAGESCRIPT - "KÖP DIN PORTFÖLJ"
						jQuery('body').append('<img src="http://rms.admeta.com/public/probe.asp?tag_id=17189&checksum=1831824117&java=true&slump=' + new Date().getTime() + '" border="0" height="1" width="1">');
						
						jQuery('#cart-buy').modal({
							closeClass: 'close-modal',
							width: 500
							
						});
					} else {
						jQuery('#cart-buy-empty').modal({
							closeClass: 'close-modal',
							maxWidth: 350
						});
					}
					return false;
				});
								
			},
			
			updateCart: function(item) {
				
				var briefcase  = new m.Briefcase;
				var cookie     = new application.Cookies;
				var itemsArr   = new Array();
				var offerId    = jQuery('#offers-id').val();
				var cookieName = 'briefcase-items-' + offerId;
				
				briefcase.animateItem(item.parent());
				briefcase.calculateOfferSum(item);
				briefcase.calculateTotalOfferSum();
				briefcase.calculateProfit();
				
				jQuery('#briefcase #cart input[type="text"]').each( function(){
					itemsArr.push(jQuery(this).val());
				});
				
				cookie.edit(cookieName, itemsArr);
				
			},
			
			/* CREATE SLIDERS IN "ADVANCED VIEW" */
			createSliders: function() {
															
				jQuery('#briefcase #cart li').each( function(index){
									
					//if ( jQuery(this).find('.offer-type').html() != 'Valutaobligation' ) {
					
						if (jQuery.cookie('slider-position') != '0') {
							var sliderValue = jQuery.cookie('slider-position').split(',');
							sliderValue = sliderValue[index];
						} else {
							var sliderValue = 7;
						}
					
						(sliderValue >= 0) ? cssClass = 'positive' : cssClass = 'negative';
											
						var itemId      = '#' + jQuery(this).attr('id');
						var sliderId    = itemId + '-slider';
						var sliderName  = jQuery(this).attr('id') + '-slider';
						var valueId     = itemId + '-sum';
						var valueName   = jQuery(this).attr('id') + '-sum';
						var briefcase   = new m.Briefcase;
						var cookie      = new m.Cookies;
					
						jQuery(itemId).append('<div class="slider-container advanced-calculator"><div class="slider calculate" id="' + sliderName + '"></div><span sum="' + sliderValue + '" class="value ' + cssClass + '" id="' + valueName + '">' + sliderValue + '%</span></div>');
					
						jQuery(sliderId).slider( {
    						min: -7, 
    						max: 15,
    						value: sliderValue,
							slide: function(e, ui){
								var sum = ui.value;
								jQuery(valueId).attr('sum', sum).html(sum + '%');
								(sum >= 0) ? jQuery(valueId).removeClass('negative').addClass('positive') : jQuery(valueId).removeClass('positive').addClass('negative');
								cookie.editSliderCookie();
								briefcase.calculateProfit();
							}
						});
						
					//}
													
				});
								
			},
			
			/* SHOW HIDE "ADVANCED VIEW" */
			showHideCalculation: function(state) {
				
				var cookie         = new application.Cookies;
				var copySimpleMode = 'Fyll i önskat antal av respektive alternativ i det aktuella erbjudandet nedan. ';
				var copyAdvMode    = 'Dra i reglagen och ange hur mycket du tror respektive marknad stiger eller faller per år. Resultatet visas nedan. ';
				
				if (state == 'advanced') {
					jQuery('#briefcase-info span').html(copyAdvMode);
					jQuery('#calculate-button').val('Tillbaka till enkelt läge');
					jQuery('#refund-sum').addClass('highlight');
					jQuery('#investment-sum').removeClass('highlight');
					jQuery('#briefcase').find('.advanced-calculator').slideDown('fast');
					jQuery('#information-text').show();
					
					// ADMETA PAGESCRIPT - "PROVRÄKNA PÅ PORTFÖLJEN"
					jQuery('body').append('<img src="http://rms.admeta.com/public/probe.asp?tag_id=17191&checksum=9719792886&java=true&slump=' + new Date().getTime() + '" border="0" height="1" width="1">');
										
					cookie.edit('briefcase-state', 'advanced');
				} else {
					jQuery('#briefcase-info span').html(copySimpleMode);		
					jQuery('#calculate-button').val('Provräkna på portföljen');
					jQuery('#investment-sum').addClass('highlight');
					jQuery('#refund-sum').removeClass('highlight');
					jQuery('#briefcase').find('.advanced-calculator').slideUp('fast');
					jQuery('#information-text').hide();
					cookie.edit('briefcase-state', 'simple');
				}				
						
			},
			
			/* SHOW HIDE FORMS UNDER BRIEFCASE */
			showHideForms: function() {
								
				jQuery('.briefcase-menu h5').wrapInner('<a href="#" class="arrow"></a>');
				
				jQuery('.briefcase-menu h5 a').each( function(){
					jQuery(this).parent().next().css({'display':'block','float':'left'}).hide();
				});
				
				/* ASIGN ACTIONS TO LINKS */
				jQuery('.briefcase-menu h5 a').bind('click', function() {
					jQuery(this).toggleClass('active');
					jQuery(this).parent().next().slideToggle('fast');
					return false;
				});
				
			},
			
			/* SHOW HIDE INFORMATION ABOUT BRIEFCASE */
			showHideInfo: function() {
	
				var cookie = new application.Cookies;
				(jQuery.cookie('briefcase-info') == 'visible') ?	jQuery('#briefcase-info').show() : jQuery('#briefcase-info').hide();
				
				/* TOGGLE BRIEFCASE INFO */
				jQuery('#link-show-hide-info-briefcase').live('click', function(){
					if (jQuery.cookie('briefcase-info') == 'visible') {
						jQuery('#briefcase-info').slideUp('fast');
						cookie.edit('briefcase-info', 'hidden');
					} else if (jQuery.cookie('briefcase-info') == 'hidden') {
						jQuery('#briefcase-info').slideDown('fast');
						cookie.edit('briefcase-info', 'visible');
					}
					return false;
				});
				
				/* HIDE BRIEFCASE INFO */
				jQuery('#briefcase-info a').bind('click', function(){
					jQuery(this).parent().slideUp('fast');
					cookie.edit('briefcase-info', 'hidden');
					return false;
				});
				
			},
			
			/* SET EFFECT TO SELECTED ITEM */
			animateItem: function(item) {
				var color  = '#5e94c6';
				var effect = 'highlight';
				var speed  = 2000;
				item.effect(effect, {color: color}, speed);
			},
			
			/* RESET BRIEFCASE */		
			reset: function() {
								
				jQuery('#cart-reset').modal({
					closeClass: 'close-modal',
					maxWidth: 350,
					onShow: function (dialog) {
						jQuery('#cart-reset input[type="button"]').bind('click', function(){
							
							jQuery('#briefcase #cart li').each( function(){
								jQuery(this).attr('sum', '0');
								jQuery(this).find('input[type="text"]').val('0');
								jQuery(this).find('label .comma').remove();
								jQuery(this).find('label .offer-sum').empty();
							});
							
							jQuery('#briefcase #calculate #investment-sum, #briefcase #calculate #payback-sum, #briefcase #calculate #refund-sum').find('p').html('0 kr').attr('sum', '0');
							
							var cookie     = new application.Cookies;
							var itemsArr   = new Array();
							var offerId    = jQuery('#offers-id').val();
							var cookieName = 'briefcase-items-' + offerId;
							
							jQuery('#briefcase #cart input[type="text"]').each( function() {
								itemsArr.push(jQuery(this).val());
							});
							
							cookie.edit(cookieName, itemsArr);
							
							jQuery.modal.close();
							
						});
					}
				});

			},
			
			/* CALCULATE EACH PRODUCTS SUM */
			calculateOfferSum: function(item) {				
				
				/* NEW CALCULATE OFFER SUM - NOT IMPLEMENTED
				
				var blockprice          = parseInt( item.parent().metadata().blockprice );
				var overpricepercentage = parseInt( item.parent().metadata().overpricepercentage ) / 100;
				var items               = parseInt( item.val() );
				var sum                 = items * (blockprice * overpricepercentage);
				
				item.parent().attr('sum', sum);
				item.parent().find('label .comma').remove();
				item.parent().find('label .offer-sum').empty();
				
				if ( sum > 0 ){
					item.parent().find('label .offer-sum').text('totalt ' + sum + ' kr').before('<span class="comma">, </span>');
				}
				*/
				
				var activeItemsArr   = jQuery('#active-offers').val().split(',');
				
				jQuery.each(activeItemsArr, function(index, value){
					
					var item = jQuery('#list-offer-' + value);
			
					item.find('label .comma').remove();
					item.find('label .offer-sum').empty();
					
					if (item.find('#offer-' + value).val() != 0) {
						var blockprice          = parseInt( item.find('#blockprice-' + value).val() );
						var overpricepercentage = parseInt( item.find('#overpricepercentage-' + value).val() ) / 100;
						var items               = parseInt( item.find('#offer-' + value).val() );
						var sum                 = items * (blockprice * overpricepercentage);
						
						jQuery('#sum-' + value).val(sum);
						item.find('label .offer-sum').text('totalt ' + formatCurrency(sum) + ' kr').before('<span class="comma">, </span>');
					} else {
						jQuery('#sum-' + value).val('0');
					}
					
				});
							
			},
			
			/* CALCULATE SELECTED PRODUCTS TOTAL SUM */
			calculateTotalOfferSum: function() {
				
				/* NEW CALCULATE TOTAL OFFER SUM - NOT IMPLEMENTED
				
				var sum          = 0;
				var totSum       = 0;	
				var courtage     = 0;
				var totCourtage  = 0;
				var overPrice    = 0;
				var totOverPrice = 0;
				var pay          = 0;
				var payback      = 0;
				var blockprice   = 0;
				var items        = 0;
								
				jQuery('#briefcase #cart li').each( function() {
					
					sum                 = parseInt(jQuery(this).attr('sum') );
					blockprice          = parseInt(jQuery(this).blockprice);
					items               = parseInt(jQuery(this).find('input[type="text"]').val());
					overpricepercentage = parseInt(jQuery(this).metadata().overpricepercentage);
					
					if ( overpricepercentage > 100 ) {
						overPrice = sum - (blockprice * items);
					}
					
					totSum	     = totSum + sum;
					courtage     = (parseInt( jQuery(this).metadata().courtage) / 100 ) * sum;
					totCourtage  = totCourtage + courtage;
					totOverPrice = totOverPrice + overPrice;
					pay          = totSum + totCourtage;
											
				});
				
				jQuery('#investment-sum p').text( formatCurrency(pay) + ' kr').attr('sum', pay); 
				*/
				
				var sum            = 0;
				var totSum         = 0;	
				var courtage       = 0;
				var totCourtage    = 0;
				var overPrice      = 0;
				var totOverPrice   = 0;
				var pay            = 0;
				var payback        = 0;
				var activeItemsArr = jQuery('#active-offers').val().split(',');
				
				jQuery.each(activeItemsArr, function(index, value){
					
					(jQuery('#sum-' + value).val() != '') ? sum = parseInt( jQuery('#sum-' + value).val() ) : sum = 0;
					
					totSum = totSum + sum;
					
					if ( parseInt( jQuery('#overpricepercentage-' + value).val() ) > 100 ) {
						overPrice = sum - ( parseInt( jQuery('#blockprice-' + value).val() ) * jQuery('#offer-' + value).val() );
					}
					
					courtage     = parseInt( jQuery('#courtage-' + value).val() ) / 100;
					courtage     = courtage * sum;
					totCourtage  = totCourtage + courtage;
					totOverPrice = totOverPrice + overPrice;
					
				});
				
				pay = totSum + totCourtage;
				jQuery('#investment-sum p').attr('sum', pay).text(formatCurrency(pay) + ' kr');
				
			},
			
			/* CALCULATE SELECTED PRODUCTS PROFIT */
			calculateProfit: function() {
				
				/* NEW CALCULATE PROFIT - NOT IMPLEMENTED
				
				var marknadstvar                = 0;
				var marknadsutv                 = 0;
				var tak                         = 0;
				var avkastningvidborsuppgang    = 0;
				var sumAvkastningvidborsuppgang = 0;
				var loptid                      = 0;
				var blockprice                  = 0;
				var antalposter                 = 0;
				var upprakningsfaktor           = 0;
				var placeratbelopp              = 0;
				var courtage                    = 0;
				var overpricepercentage         = 0;
				var vinst                       = 0;
				var sumVinst                    = 0;
				var refund                      = 0;
				var sumRefund                   = 0;
				var payback                     = 0;
				var sumPayback                  = 0;

				jQuery('#briefcase #cart li').each( function() {
					
					var items = parseInt(jQuery(this).find('input[type="text"]').val());
					
					if ( items != 0) {
						
						marknadsutv   = parseInt(jQuery(this).find('.slider-container span').attr('sum')) / 100 + 1;
						tak           = parseInt(jQuery(this).metadata().limit);
						loptid        = parseInt(jQuery(this).metadata().time) / 360;
						marknadsutvar = Math.pow(marknadsutv, loptid) - 1;
						
						if (tak != 0){
							if (marknadsutvar > tak) {
								marknadsutvar = tak;
							}
						}
																
						courtage            = parseInt(jQuery(this).metadata().courtage) / 100;
						overpricepercentage = parseInt(jQuery(this).metadata().overpricepercentage) / 100
						blockprice          = parseInt(jQuery(this).metadata().blockprice);
						upprakningsfaktor   = parseInt(jQuery(this).metadata().factorpercentage) / 100;
						vinst               = (blockprice * items) * upprakningsfaktor * marknadsutvar; 
						placeratbelopp      = blockprice * items;						
						sumPayback          = sumPayback + placeratbelopp;
													
						if (vinst <= 0) {
							vinst     = (blockprice * items) - ((blockprice * overpricepercentage * courtage * items) + (blockprice * items));
							sumVinst  = sumVinst + vinst;
							refund    = blockprice * items;
							sumRefund = sumRefund + refund;
						} else {
							sumVinst  = sumVinst + vinst;		
							refund    = placeratbelopp + vinst
							sumRefund = sumRefund + refund;
						}
						
					}
										
					jQuery('#payback-sum p').text( formatCurrency(sumPayback) + ' kr').attr('sum', sumPayback);
					jQuery('#refund-sum p').text( formatCurrency(sumRefund) + ' kr' ).attr('sum', sumRefund);
					
				});	
				*/
					
	    		var marknadsutvar               = 0;
	    		var marknadsutv                 = 0;
	    		var tak                         = 0;
	    		var avkastningvidborsuppgang    = 0;
				var sumAvkastningvidborsuppgang = 0;
	    		var vinst                       = 0;
	    		var sumVinst                    = 0;
	    		var refund                      = 0;
	    		var sumRefund                   = 0;
	    		var loptid                      = 0;
	    		var blockprice                  = 0;
	    		var antalposter                 = 0;
	    		var upprakningsfaktor           = 0;
	    		var placeratbelopp              = 0;
	    		var courtage                    = 0;
	    		var overpricepercentage         = 0;
	    		var payback                     = 0;
	    		var sumPayback                  = 0;
	    		var activeItemsArr              = jQuery('#active-offers').val().split(',');
	    			    		
	    		jQuery.each(activeItemsArr, function(index, value){
	    			    			
	    			if (parseInt(jQuery('#offer-' + value).val()) != 0) {
	    				
	    				antalposter   = parseInt( jQuery('#offer-' + value).val());
	    				marknadsutv   = ( parseInt( jQuery('#list-offer-' + value).find('.slider-container span.value').attr('sum') ) / 100 ) + 1; 
	    				tak           = parseInt(jQuery('#limit-' + value).val()) / 100;
	    				loptid        = parseInt(jQuery('#time-' + value).val()) / 360;
	    				marknadsutvar = Math.pow(marknadsutv, loptid) - 1;
	    				
	    				if (tak != 0) {
	    					if (marknadsutvar > tak) {
	    						marknadsutvar = tak;
	    					}			
	    				}
	    				
	    				courtage            = parseInt( jQuery('#courtage-' + value).val() ) / 100;
	    				overpricepercentage = parseInt(jQuery('#overpricepercentage-' + value).val()) / 100
	    				blockprice          = parseInt(jQuery('#blockprice-' + value).val());
	    				antalposter         = parseInt(jQuery('#offer-' + value).val());
	    				upprakningsfaktor   = parseInt(jQuery('#factorpercentage-' + value).val()) / 100;
	    				vinst               = (blockprice * antalposter) * upprakningsfaktor * marknadsutvar; 
	    				placeratbelopp      = blockprice * antalposter;
	    				sumPayback          = sumPayback + placeratbelopp;
	    				
	    				if (vinst <= 0) {
	    					vinst = (blockprice * antalposter) - ( (blockprice * overpricepercentage * courtage * antalposter) + (blockprice * antalposter) );
	    					sumVinst = sumVinst + vinst;
	    					refund = blockprice * antalposter;
	    					sumRefund = sumRefund + refund;
	    				} else {
	    					sumVinst = sumVinst + vinst;		
	    					refund = placeratbelopp + vinst
	    					sumRefund = sumRefund + refund;
	    				}
	    				
	    				jQuery('#payback-sum p').attr('sum', sumPayback).text(formatCurrency(sumPayback) + ' kr');
	    				jQuery('#refund-sum p').attr('sum', sumRefund).text( formatCurrency(sumRefund) + ' kr' );

	    				sumVinstTxt = parseInt(jQuery('#refund-sum p').attr('sum')) - parseInt(jQuery('#investment-sum p').attr('sum'));
	    			
	    				jQuery('#profit-sum p').attr('sum', sumVinst).text( formatCurrency(sumVinstTxt) + ' kr' );
	    		
	    			}
	    			
	    		});
						
			},
			
			preDefined: function() {

				jQuery('#btn-buy-cart-small, #btn-buy-cart-medium, #btn-buy-cart-large').bind('click', function(){
					/*MakeBuyLinks();
					$('#cart-buy').modal({
						closeClass: 'close-modal',
						width: 500
					});*/
					
					var briefcase  = new m.Briefcase;
					var itemsArr   = jQuery(this).metadata().items.split(',');
					var offerId    = jQuery('#offers-id').val();
					var cookieName = 'briefcase-items-' + offerId;
					var tempArr    = jQuery.cookie(cookieName).split(',');
					var itemsStr   = itemsArr.join(',');
					var tempStr    = tempArr.join(',');
					var tempItems  = 0;
					
					jQuery('#briefcase #cart input[type="text"]').each( function(){
						tempItems = tempItems + parseInt(jQuery(this).val());
					});
					
					jQuery('#briefcase #cart input[type="text"]').each( function(index){
						if (jQuery(this).val() != itemsArr[index]){
							jQuery(this).val(itemsArr[index]);
							briefcase.showHideCalculation('advanced');
							briefcase.updateCart(jQuery(this));
						}
					});
				
					jQuery("#form-cart").trigger('submit');
				});
				
			}
			
		}
	});

	Class('Forms', {
		methods: {
			
			init: function() {

				var id    = '';
				var title = '';
				jQuery('#savecart, #sendcart, #remindme, #subscribe, #tip-a-friend-top, #report-comment, #write-a-comment, #ask-a-question, #tip-a-friend-bottom, #tip-a-friend-small, #tip-a-friend-medium, #tip-a-friend-large').find('input.required, textarea.required').each( function(){
					(jQuery(this).attr('type') == 'checkbox') ? id = jQuery(this).attr('name') : id = jQuery(this).attr('id');
					title = jQuery(this).attr('title').slice(0, -1);
					(title == 'Formulera gärna din fråga så precist det går, så får du ett bättre svar') ? title = 'Din fråga' : title = title;
					if (id == 'questionnewsletteraccept' || id == 'commentxda') {
						jQuery(this).parent().parent().parent().find('.error.client').addClass('js-generated').append('<label for="' + id + '" class="error"><i>- ' + title + '</i></label>\n');
					} else {
						jQuery(this).parent().parent().find('.error.client').addClass('js-generated').append('<label for="' + id + '" class="error"><i>- ' + title + '</i></label>\n');
					}
				});

			},
			
			labelify: function() {
				
				jQuery('label:not(.checkbox-container label, .question-of-the-week label, .briefcase .cart label, .cart-buy label, .underlyings label)').hide();
				jQuery('input[type="text"], textarea').labelify();
				
			},
			
			rules: function() {
								
				jQuery.validator.addMethod('your_name', function(val) { 
					return val != 'Ditt namn *'; 
				});
				
				jQuery.validator.addMethod('your_email', function(val) { 
					return val != 'Din e-postadress *'; 
				});
				
				jQuery.validator.addMethod('reciever_name', function(val) { 
					return val != 'Din väns namn *'; 
				});
				
				jQuery.validator.addMethod('reciever_email', function(val) { 
					return val != 'Din väns e-postadress *';
				});
				
				jQuery.validator.addMethod('report_reason', function(val) { 
					return val != 'Anledning till anmälan *';
				});
				
				jQuery.validator.addMethod('comment_text', function(val) { 
					return val != 'Din kommentar *';
				});
				
				jQuery.validator.addMethod('question_text', function(val) { 
					return val != 'Formulera gärna din fråga så precist det går, så får du ett bättre svar!';
				});
				
				jQuery.validator.addMethod('comment_captcha', function(val) { 
					return val != 'Bildtexten *';
				});
												
			},
			
			validate: function() {
							
				/* TIP A FRIEND - TOP */
				jQuery('#tip-a-friend-top form').validate({
					rules: {
		            	sendtofriendyourname_top: 'your_name',
		            	sendtofriendyouremail_top: 'your_email',
		            	sendtofriendfriendname_top: 'reciever_name',
		            	sendtofriendfriendemail_top: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#friend-error-client-top'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								//responseSendcart(response, jQuery('#friend-error-server-top'), jQuery('#friend-feedback-top'));
								jQuery('#friend-feedback-top').slideDown('fast');
							}
						});
					}
				});
				
				/* TIP A FRIEND - BOTTOM */
				jQuery('#tip-a-friend-bottom form').validate({
					rules: {
		            	sendtofriendyourname_bottom: 'your_name',
		            	sendtofriendyouremail_bottom: 'your_email',
		            	sendtofriendfriendname_bottom: 'reciever_name',
		            	sendtofriendfriendemail_bottom: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#friend-error-client-bottom'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								//responseSendcart(response, jQuery('#friend-error-server-bottom'), jQuery('#friend-feedback-bottom'));
								jQuery('#friend-feedback-bottom').slideDown('fast');
							}
						});
					}
				});
				
				/* TIP A FRIEND - BRIEFCASE SMALL */
				jQuery('#tip-a-friend-small form').validate({
					rules: {
		            	sendtofriendyourname_small: 'your_name',
		            	sendtofriendyouremail_small: 'your_email',
		            	sendtofriendfriendname_small: 'reciever_name',
		            	sendtofriendfriendemail_small: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#friend-error-client-small'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								//responseSendcart(response, jQuery('#friend-error-server-small'), jQuery('#friend-feedback-small'));
								jQuery('#friend-feedback-small').slideDown('fast');
							}
						});
					}
				});
				
				/* TIP A FRIEND - BRIEFCASE MEDIUM */
				jQuery('#tip-a-friend-medium form').validate({
					rules: {
		            	sendtofriendyourname_medium: 'your_name',
		            	sendtofriendyouremail_medium: 'your_email',
		            	sendtofriendfriendname_medium: 'reciever_name',
		            	sendtofriendfriendemail_medium: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#friend-error-client-medium'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								//responseSendcart(response, jQuery('#friend-error-server-medium'), jQuery('#friend-feedback-medium'));
								jQuery('#friend-feedback-medium').slideDown('fast');
							}
						});
					}
				});
				
				/* TIP A FRIEND - BRIEFCASE LARGE */
				jQuery('#tip-a-friend-large form').validate({
					rules: {
		            	sendtofriendyourname_large: 'your_name',
		            	sendtofriendyouremail_large: 'your_email',
		            	sendtofriendfriendname_large: 'reciever_name',
		            	sendtofriendfriendemail_large: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#friend-error-client-large'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								//responseSendcart(response, jQuery('#friend-error-server-large'), jQuery('#friend-feedback-large'));
								jQuery('#friend-feedback-large').slideDown('fast');
							}
						});
					}
				});
				
				/* BRIEFCASE SAVE BRIEFCASE */
				jQuery('#savecart form').validate({
					rules: {
		            	save_cart_email: 'your_email'
		            },
					errorLabelContainer: jQuery('#savecart-error-client'),
					submitHandler: function(form) {
						populateDataToPost("#savecartdata");
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoSave(response);
							}
						});
					}
				});
				
				/* BRIEFCASE - SEND BRIEFCASE SMALL */
				jQuery('#sendcart-small form').validate({
					rules: {
		            	sendcartyourname_small: 'your_name',
		            	sendcartyouremail_small: 'your_email',
		            	sendcartfriendname_small: 'reciever_name',
		            	sendcartfriendemail_small: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#sendcart-small-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseSendcartSmall(response);
							}
						});
					}
				});
				
				/* BRIEFCASE - SEND BRIEFCASE MEDIUM */
				jQuery('#sendcart-medium form').validate({
					rules: {
		            	sendcartyourname_medium: 'your_name',
		            	sendcartyouremail_medium: 'your_email',
		            	sendcartfriendname_medium: 'reciever_name',
		            	sendcartfriendemail_medium: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#sendcart-medium-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseSendcartMedium(response);
							}
						});
					}
				});
				
				/* BRIEFCASE - SEND BRIEFCASE LARGE */
				jQuery('#sendcart-large form').validate({
					rules: {
		            	sendcartyourname_large: 'your_name',
		            	sendcartyouremail_large: 'your_email',
		            	sendcartfriendname_large: 'reciever_name',
		            	sendcartfriendemail_large: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#sendcart-large-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseSendcartLarge(response);
							}
						});
					}
				});
				
				/* BRIEFCASE - SEND BRIEFCASE */
				jQuery('#sendcart form').validate({
					rules: {
		            	sendcartyourname: 'your_name',
		            	sendcartyouremail: 'your_email',
		            	sendcartfriendname: 'reciever_name',
		            	sendcartfriendemail: 'reciever_email'
		            },
					errorLabelContainer: jQuery('#sendcart-error-client'),
					submitHandler: function(form) {
						populateDataToPost("#sendcartdata");
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseSendcart(response);
							}							
						});
					}
				});
				
				/* BRIEFCASE - REMIND ME */
				jQuery('#remindme form').validate({
					rules: {
		            	remindmeemail: 'your_email'
		            },
					errorLabelContainer: jQuery('#remindme-error-client'),
					submitHandler: function(form) {
						populateDataToPost("#remindcartdata");
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoRemind(response);
							}
						});
					}
				});
				
				/* NEWSLETTER */		
				jQuery('#subscribe form').validate({
					rules: {
						subscribeemail: 'your_email',
						newsletterchoice: {
							required: true,
							minlength: 1
						}
		            },
					errorLabelContainer: jQuery('#subscribe-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoSubscribe(response);
								
								// ADMETA PAGESCRIPT - "NYHETSBREV"
            					jQuery('body').append('<img src="http://rms.admeta.com/public/probe.asp?tag_id=17196&checksum=8618692875&java=true&slump="' + new Date().getTime() + '" border="0" height="1" width="1">');
							
							}
						});
					}
				});
								
				/* REPORT A COMMENT */					
				jQuery('#report-comment form').validate({
					rules: {
		            	reportemail: 'your_email',
		            	reportreason: 'report_reason'		            	
		            },
					errorLabelContainer: jQuery('#report-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoReport(response);
								setTimeout('jQuery.modal.close()', 3000);
							}
						});
					}
				});
				
				/* WRITE A COMMENT */
				jQuery('#write-a-comment form').validate({
					rules: {
		            	commenttext: 'comment_text',
		            	commentname: 'your_name',
		            	commentemail: 'your_email',
		            	commentxda: 'comment_captcha'
		            },
					errorLabelContainer: jQuery('#comment-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoComment(response);
							}
						});
					}
				});
				
				/* ASK A QUESTION */
				jQuery('#ask-a-question form').validate({
					rules: {
		            	questiontext: 'question_text',
		            	questionemail: 'your_email',
						questionnewsletteraccept: {
							required: function() { return jQuery('#questionnewsletterTwo:checked').val() != null || jQuery('#questionnewsletterOne:checked').val() != null }
						}
		           	},
					errorLabelContainer: jQuery('#question-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								responseDoAskQuestion(response);
							}
						});
					}
				});
				
				/* QUESTION OF THE WEEK */
				jQuery('#question-of-the-week form').validate({
					errorLabelContainer: jQuery('#question-of-the-week-error-client'),
					submitHandler: function(form) {
						jQuery(form).ajaxSubmit({
							success: function(response){
								var cookie = new application.Cookies;
								var id     = jQuery('#question-id').val();
								cookie.edit('qestion-of-the-week-' + id, true);
								responseDoAnswerQuestion(response);
							}
						});
					}
				});
							
			}
		}
	});
	
	Class('Cookies', {
		isa: m.Briefcase,
		methods: {
			init: function (){
				
				var cookie      = new application.Cookies;
				var offerId     = jQuery('#offers-id').val();
				var questionId  = jQuery('#question-id').val();
				var cookieName  = '';
				var cookieValue = '';
							
				if (jQuery.cookie('briefcase-state') == null) {
					cookieName  = 'briefcase-state';
					cookieValue = 'simple';
					cookie.edit(cookieName, cookieValue, 10);
				};
		
				var cookieName = 'briefcase-items-' + offerId;
				if (jQuery.cookie(cookieName) == null) {
					var itemsArr = new Array();
					jQuery('#briefcase #cart input[type="text"]').each( function(){
						itemsArr.push(jQuery(this).val());
					});
					cookie.edit(cookieName, itemsArr, 10);
				};
				
				if (jQuery.cookie('briefcase-info') == null) {
					cookieName  = 'briefcase-info';
					cookieValue = 'hidden';
					cookie.edit(cookieName, cookieValue, 10);
				};
				
				if (jQuery.cookie('slider-position') == null) {
					cookieName  = 'slider-position';
					cookieValue = '0';
					cookie.edit(cookieName, cookieValue, 10);
				};

				var cookieName = 'qestion-of-the-week-' + questionId;
				if (jQuery.cookie(cookieName) == null) {
					cookieValue = false;
					cookie.edit(cookieName, cookieValue, 100);
				}
		
			},
			
			edit: function  (name, value, exp){
            	jQuery.cookie(name, value, { expires: exp, path: '/' });
			},
			
			editSliderCookie: function(){
				
				var sliderArr = new Array();
				var cookie    = new application.Cookies;
				jQuery('#briefcase #cart fieldset li').each( function(){
					sliderArr.push( jQuery(this).find('.slider-container span.value').attr('sum') );
				});
				cookie.edit('slider-position', sliderArr);
					
			},
			
			kill: function (name){
				jQuery.cookie(name, null);
			}
			
		}
	});

});