$(document).ready(function() {
	if ($('#log_in div.tab a').length == 0)
		$('#log_in div.tab').click(toggleLogIn);
});

sendNewPassword = function() {
	$.getJSON('/ajax/sendNewPassword/', { email : $('#forgot_email').val() }, function(data) {
		if (data.message == 'FAILED') {
			$('#newpassord span').show();
		} else {
			$("#newpassord").fadeOut("normal", function() {
				$("#hide").fadeIn();
			});
		}
	});
}

// GRID 960
createGridder = function() {
	document.body.appendChild(document.createElement('script')).src='http://gridder.andreehansson.se/releases/latest/960.gridder.js';
}

// Function to handle all types of messages
message = function(type, data) {
	// If top layer doesn't exists
	if ($('#top-layer').length == 0) {
		// Create top layer background
		$('body').append('<div id="top-layer" onclick="closeMessageBox();"></div>');
		
		// Create top layer content
		$('body').append('<div id="top-layer-content"><a href="javascript:void(0);" onclick="closeMessageBox();" class="close"></a><div class="title"></div><div class="content"></div></div>');
	}
		
	// Set same height as document
	$('#top-layer').css({ 'height' : $(document).height() + 'px' });
	
	// If width is sent into the function
	if (data.width > 0) {
		$('#top-layer-content').css({ 'width' : data.width + 'px' });
	}
	
	// Set top position for content
	$('#top-layer-content').css({ 'top' : ($(window).scrollTop() + 50) + 'px' });
	
	// Set correct content
	$('#top-layer-content div.title').text(data.title);
	
	if (data.html) {
		$('#top-layer-content div.content').html(data.message);
	} else {		
		$('#top-layer-content div.content').text(data.message);
	}
	
	// Hide error message
	$('#top-layer-content div.error').hide();
	
	// Show top layer
	$('#top-layer').show();
	$('#top-layer-content').show();
}

closeMessageBox = function() {
	$('#top-layer').hide();
	$('#top-layer-content').hide();
}

var log_in_margin_top = 0;

toggleLogIn = function() {
	$('#log_in').animate({ 'margin-top' : log_in_margin_top + 'px' }, 500);
	
	if (log_in_margin_top == 0) {
		log_in_margin_top = -110;
	} else {
		log_in_margin_top = 0;
	}
}

submitLogin = function() {
	var email = $('#login_email').val();
	var password = $('#login_password').val();
	
	$.getJSON('/ajax/checkLoginData/', { 'email' : email, 'password' : password }, function(data) {
		if (data.message == 'INCORRECT_DATA') {
			message('error', { 'title' : 'Felaktiga uppgifter', 'message' : 'Du har angett felaktiga inloggningsuppgifter, försök igen!' });
		} else {
			$('#login_form').submit();
		}
		
	});
}

getPage = function(page) {
	$.getJSON('/ajax/getPage/', { 'page' : page }, function(data) {
		if (data) {
			message('information', { 'title' : data.title, 'message' : data.html, 'html' : true});
			$('#top-layer-content table tr:odd').addClass('odd');
		}
	});
}

elementExists = function(obj) {
	if ($(obj).length == 0) {
		return false;
	} else {
		return true;
	}
}

strReplace = function(search, replace, subject, count) {
	f = [].concat(search),
	r = [].concat(replace),
	s = subject,
	ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
	
	if (count) {
		this.window[count] = 0;
	}
	
	for (i=0, sl=s.length; i < sl; i++) {
		if (s[i] === '') {
			continue;
		}
		
		for (j=0, fl=f.length; j < fl; j++) {
			temp = s[i]+'';
			repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
			s[i] = (temp).split(f[j]).join(repl);
		
			if (count && s[i] !== temp) {
				this.window[count] += (temp.length-s[i].length)/f[j].length;
			}
		}
	}
	
    return sa ? s : s[0];
}

validateForms = function() {
	var error = '';
	
	if (elementExists('#type_electricity')) {
		// Check if some of the contract types is checked
		if ($('#type_electricity').is(':checked') == false && $('#type_petrol').is(':checked') == false) {
			error = '<li>Du måste ange minst ett avtal att teckna.</li>';
		}
	}
	
	if (elementExists('#company_name')) {
		if ($('#company_1').is(':checked') && $('#company_name').val().length == 0) {
			error += '<li>Du måste ange firmanamn/BRF</li>';
		}
	}
	
	if (elementExists('#first_name')) {
		// Check first name
		if ($('#first_name').val().length == 0) {
			error += '<li>Du måste ange ditt förnamn.</li>';
		}
	}
	
	if (elementExists('#last_name')) {
		// Check last name
		if ($('#last_name').val().length == 0) {
			error += '<li>Du måste ange ditt efteramn.</li>';
		}
	}
	
	if (elementExists('#email')) {
		// Check so email address is correct
		if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($('#email').val())) {
			$.ajax({
				url : '/ajax/checkEmail/',
				dataType : 'json',
				async : false,
				type : 'GET',
				data: ({ email : $('#email').val() }),

				success: function(data) {
					if (data.message == 'ALREADY_EXISTS') {
						error += '<li>E-postadressen du angav finns redan registrerat hos oss.</li>';
					}
				}
			});
		} else {
			error += '<li>Du har angett en felaktig e-postadress.</li>';
		}
	}
	
	if (elementExists('#phone')) {
		// Check if phone number is empty
		if ($('#phone').val().length == 0) {
			error += '<li>Du måste ange ett telefonnummer.</li>';
		// If not empty, check so it only contains digits
		} else if (!/^\d+$/.test($('#phone').val())) {
			error += '<li>Telefonnumret får endast innehålla siffror.</li>';
		}
	}
	
	if (elementExists('#cell_phone')) {
		// If cell phone not is empty, check so it only contains digits
		if ($('#cell_phone').val().length > 0 && !/^\d+$/.test($('#cell_phone').val())) {
			error += '<li>Mobilnumret får endast innehålla siffror.</li>';
		}
	}
	
	if (elementExists('#address')) {
		// Check if address is empty
		if ($('#address').val().length == 0) {
			error += '<li>Du måste ange din adress.</li>';
		}
	}
	
	if (elementExists('#zipcode')) {
		// Check so zipcode only contains digits
		if (!/^\d+$/.test($('#zipcode').val())) {
			error += '<li>Postnumret får endast innehålla siffror.</li>';
		// Else check so it contais exact count of chars
		} else if ($('#zipcode').val().length != 5) {
			error += '<li>Postnumret måste vara exakt fem siffror lång.</li>';
		}
	}
	
	if (elementExists('#city')) {
		// Check if city is empty
		if ($('#city').val().length == 0) {
			error += '<li>Du måste ange ort.</li>';
		}
	}
	
	if (elementExists('#social_security_number')) {
		// Check so social security number only contains digits
		if (!/^\d+$/.test($('#social_security_number').val())) {
			error += '<li>' + ($('#company_1').is(':checked') ? 'Organisationsnumret' : 'Personnumret') + ' får endast innehålla siffror.</li>';
		// Else check so it contais exact count of chars
		} else if ($('#social_security_number').val().length != 10) {
			error += '<li>' + ($('#company_1').is(':checked') ? 'Organisationsnumret' : 'Personnumret') + ' måste vara exakt tio siffror lång.</li>';
		} else {
			$.ajax({
				url : '/ajax/checkSocialSecurityNumber/',
				dataType : 'json',
				async : false,
				type : 'GET',
				data: ({ ssn : $('#social_security_number').val() }),

				success: function(data) {
					if (data.message == 'ALREADY_EXISTS') {
						error += '<li>' + ($('#company_1').is(':checked') ? 'Organisationsnumret' : 'Personnumret') + ' du angav finns redan registrerat hos oss.</li>';
					}
				}
			});
		}
	}
	
	if (elementExists('#electricity_address')) {
		// Check address
		if ($('#electricity_address').val().length == 0) {
			error += '<li>Du måste ange din anläggningsadress.</li>';
		}
	}
	
	if (elementExists('#electricity_zipcode')) {
		// Check so zipcode only contains digits
		if (!/^\d+$/.test($('#electricity_zipcode').val())) {
			error += '<li>Postnumret får endast innehålla siffror.</li>';
		// Else check so it contais exact count of chars
		} else if ($('#electricity_zipcode').val().length != 5) {
			error += '<li>Postnumret måste vara exakt fem siffror lång.</li>';
		}
	}
	
	if (elementExists('#electricity_city')) {
		// Check city
		if ($('#electricity_city').val().length == 0) {
			error += '<li>Du måste ange ort.</li>';
		}
	}
	
	if (elementExists('#electricity_id')) {
		// Check for errors if value not is zero
		if ($('#electricity_id').val() != 0 || $('#electricity_id').val().length == 0) {
			// Check electricity ID
			if ($('#electricity_id').val().length == 0) {
				error += '<li>Du måste ange ditt anläggnings ID.</li>';
				// Else chech so it contains exact count of chars
			} else if ($('#electricity_id').val().length != 18) {
				error += '<li>Anläggnings ID måste vara exakt 18 siffror långt.</li>';
				// Else check so it oly contains digits
			} else if (!/^\d+$/.test($('#electricity_id').val())) {
				error += '<li>Anläggnings ID får endast innehålla siffror.</li>';
				// Else check so it starts with 735999
			} else if (!/^735999/.test($('#electricity_id').val())) {
				error += '<li>Anläggnings ID måste börja på 735 999.</li>';
			}
		}
	}
	
	if (elementExists('#electricity_netword_id')) {
		if ($('#electricity_netword_id').val() != 0 || $('#electricity_netword_id').val().length == 0) {
			// Check network ID
			if ($('#electricity_netword_id').val().length == 0) {
				error += '<li>Du måste ange ditt nätverksområdets ID.</li>';
				// Else chech so it contains exact count of chars
			} else if ($('#electricity_netword_id').val().length != 3) {
				error += '<li>Nätverksområdets ID måste vara exakt tre tecken långt.</li>';
			} else if (!/^[A-ZÅÄÖa-zåäö]+$/.test($('#electricity_netword_id').val())) {
				error += '<li>Nätverksområdets ID får endast innehålla tecken mellan A-Ö.</li>';
			}
		}
	}
	
	
	if (elementExists('#electricity_consumption')) {
		// Check consumption 
		if ($('#electricity_consumption').val().length == 0) {
			error += '<li>Du måste ange din årliga förbrukning.</li>';
		// Else check so it oly contains digits
		} else if (!/^\d+$/.test($('#electricity_consumption').val())) {
			error += '<li>Beräknad årsförbrukning får endast innehålla siffror.</li>';
		}
	}
	
	if (elementExists('#electricity_supplier')) {
		// Check electricity supplier
		if ($('#electricity_supplier').val() < 1) {
			error += '<li>Du måste ange din nuvarande leverantör.</li>';
		}
	}
	
	if (elementExists('#electricity_consumer')) {
		// Check electricity consumer
		if ($('#electricity_consumer').val() < 1) {
			error += '<li>Du måste ange typ av förbrukare.</li>';
		}
	}
	
	if (elementExists('#electricity_delivery_date')) {
		// Check delivery date
		if ($('#electricity_delivery_date').val() < 1) {
			error += '<li>Du måste ange leveransdatum.</li>';
		}
	}
	
	if (elementExists('#electricity_payment')) {
		// Check payment type
		if ($('#electricity_payment').val() < 1) {
			error += '<li>Du måste ange betalsätt.</li>';
		}
	}
	
	if (elementExists('#petrol_choice_0')) {
		if ($('#petrol_choice_1').is(':checked')) {
			// Check first station
			if ($('#petrol_first_choice').val() < 1) {
				error += '<li>Du måste ange 1:a handsvalet.</li>';
			}
		}
	}
	
	if (elementExists('#petrol_spending_limit')) {			
		// Check spending limit
		if ($('#petrol_spending_limit').val() < 1) {
			error += '<li>Du måste ange önskad köpgräns.</li>';
		}
	}
	
	var select_one_petrol_consumption = 0;
	var check_consumption = 0;
	
	if (elementExists('#petrol_consumption_gasoline')) {
		check_consumption = 1;
		
		// Check consumption for gasoline
		if (!/^\d+$/.test($('#petrol_consumption_gasoline').val())) {
			error += '<li>Månadsförbrukning av bensin får endast innehålla siffrro.</li>';
		} else if ($('#petrol_consumption_gasoline').val() > 0) {
			select_one_petrol_consumption = 1;
		}
	}
	
	if (elementExists('#petrol_consumption_diesel')) {			
		// Check consumption for gasoline
		if (!/^\d+$/.test($('#petrol_consumption_diesel').val())) {
			error += '<li>Månadsförbrukning av diesel får endast innehålla siffrro.</li>';
		} else if ($('#petrol_consumption_diesel').val() > 0) {
			select_one_petrol_consumption = 1;
		}
	}
	
	if (elementExists('#petrol_consumption_ethanol')) {			
		// Check consumption for gasoline
		if (!/^\d+$/.test($('#petrol_consumption_ethanol').val())) {
			error += '<li>Månadsförbrukning av etanol får endast innehålla siffrro.</li>';
		} else if ($('#petrol_consumption_ethanol').val() > 0) {
			select_one_petrol_consumption = 1;
		}
	}
	
	if (select_one_petrol_consumption == 0 && check_consumption == 1) {
		error += '<li>Du måste ange antal liter för någon av de tre drivmedel.</li>';
	}
	
	if (elementExists('#petrol_current_0')) {
		if ($('#petrol_current_1').is(':checked')) {
			var first_choice_station = 0, current_station_checked = 0, same_first_choice_current = 0;
			
			if ($('#petrol_choice_1').is(':checked')) {
				// Check first station
				if ($('#petrol_first_choice').val() > 0) {
					first_choice_station = $('#petrol_first_choice').val();
				}
			}
			
			// Check so at least one station is checked		
			$.each($('#petrol_current_container input[type="checkbox"]'), function(i, d) {
				if ($(d).is(':checked')) {
					current_station_checked = 1;
					
					if ($(d).val() == first_choice_station) {
						same_first_choice_current = 1;
					}
				}
			});
			
			if (current_station_checked == 0) {
				error += '<li>Du måste välja minst en station</li>';
			} else if (same_first_choice_current == 1) {
				error += '<li>Du kan inte ansöka om ett kort som du redan har</li>';
			}
		}
	}
	
	if (elementExists('#petrol_annual_income')) {
		// Check annual incomde 
		if ($('#petrol_annual_income').val().length == 0) {
			error += '<li>Du måste ange din årsinkomst.</li>';
		// Else check so it oly contains digits
		} else if (!/^\d+$/.test($('#petrol_annual_income').val())) {
			error += '<li>Årsinkomst får endast innehålla siffror.</li>';
		}
	}
	
	if (elementExists('#petrol_employer')) {
		// Check employer
		if ($('#petrol_employer').val().length == 0) {
			error += '<li>Du måste ange din arbetsgivare.</li>';
		}
	}
	
	if (elementExists('#petrol_employed_since')) {
		// Check employed since
		if ($('#petrol_employed_since').val().length == 0) {
			error += '<li>Du måste ange anställd sedan.</li>';			
		// Check so employed since only contains digits
		} else if (!/^\d+$/.test($('#petrol_employed_since').val())) {
			error += '<li>Anställd sedan får endast innehålla siffror.</li>';
		// Else check so it contais exact count of chars
		} else if ($('#petrol_employed_since').val().length != 4) {
			error += '<li>Anställd sedan måste vara exakt fyra siffror lång.</li>';
		}
	}
	
	if (elementExists('#petrol_employment_type')) {
		// Check employment type
		if ($('#petrol_employment_type').val() < 1) {
			error += '<li>Du måste ange din anställningsform.</li>';
		}
	}
	
	if (elementExists('#current_password')) {
		// Check current password
		if ($('#current_password').val().length == 0) {
			error += '<li>Du måste ange ditt nuvarande lösenord.</li>';
		// Else check so it is a correct password
		} else {
			$.ajax({
				url : '/ajax/checkPassword/',
				dataType : 'json',
				async : false,
				type : 'GET',
				data: ({ password : $('#current_password').val() }),

				success: function(data) {
					if (data.message == 'WRONG_PASSWORD') {
						error += '<li>Lösenordet du angav var felatkigt.</li>';
					}
				}
			});
		}
	}
	
	if (elementExists('#new_password')) {
		// Check new password
		if ($('#new_password').val().length == 0) {
			error += '<li>Du måste ange ett nytt lösenord.</li>';
		// Else if new password not is the same
		} else if ($('#new_password').val() != $('#new_re_password').val()) {
			error += '<li>De nya lösenorden stämmer inte överens.</li>';
		}
	}
	
	if (error != '') {
		message('error', { 'title' : 'Nu blev det lite fel', 'message' : '<ul>' + error + '</ul>', 'html' : true });
		return false
	} else {
		return true;
	}
}


shareOnFacebook = function() {
	var url = "http://www.facebook.com/sharer.php?u=http://www.kontosmart.se&t=Sveriges bästa priser på el och drivmedel?";
	
	window.open(url, "Dela", "toolbars=0, scrollbars=0, location=0, statusbars=0, menubars=0, width=550, height=330");
}

showLowestPrice = function () {
	$('#price_petrol').hide();
	$('#price_petrol_2').show();
}