//utilities
var calcPrice = function($group, $dump) {   
	//grabbing the option cost and base price to add together
	var totalPrice = 0;
	$group.each(function(i, ele) {
		totalPrice += $(ele).attr('label')*1;
	});	
	$dump.val('$' + totalPrice);
};
var toggler = function(obj, effect) {
	//toggle or hide between contact and login sections
	obj.animate({
		"height": effect,
		"marginTop": effect,
		"marginBottom": effect,
		"paddingTop": effect,
		"paddingBottom": effect
	}, 'normal', 'easeInOutSine');
	
	//Reset all slider forms after error message is hidden
	$('#errors').slideUp('slow', function() {
		$('form:eq(0), form:eq(1)', '#login')[0].reset();
		$('#contact_form').validate().resetForm();
		$('p', this).text('');
	});
};

//Global dialog popup options
var globalDialogOptions = {
	show: 'scale',
	autoOpen: false,
	modal: true,
	closeText: '',
	open: function() {
		var $this = $(this);
		$('.ui-widget-overlay').click(function() {
			$this.dialog('close');
		});
		$(window).resize(function() {
			$this.dialog('option', 'position', ['center', 'center']);
		});
	},
	close: function() {
		//Reset incase user moves box
		$(this).dialog('option', 'position', ['center', 'center']).html('');
	}
};

//jQuery validator plugin - additional methods
jQuery.validator.addMethod("alphamumeric", function(value, element) {
	return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value);
}, "Letters and numbers only"); 
jQuery.validator.addMethod("nospaces", function(value, element) {
	return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please"); 

$(document).ready(function() {
	//Reset all package forms on load
	if($('#packages').length) {
		$("input[name$='processor_cid']").val($("select[name$='processor'] option:eq(0)").attr("class"));
		$("input[name$='hard_drive_cid']").val($("select[name$='hard_drive'] option:eq(0)").attr("class"));
		$("input[name$='memory_cid']").val($("select[name$='memory'] option:eq(0)").attr("class"));
		$("input[name$='raid_cid']").val($("select[name$='raid'] option:eq(0)").attr("class"));
		$("input[name$='os_cid']").val($("select[name$='os'] option:eq(0)").attr("class"));
		$("input[name$='control_panel_cid']").val($("select[name$='control_panel'] option:eq(0)").attr("class"));
		$("input[name$='ip_address_cid']").val($("select[name$='ip_address'] option:eq(0)").attr("class"));
		$("input[name$='bandwidth_cid']").val($("select[name$='bandwidth'] option:eq(0)").attr("class"));
		$.each($('form', '#packages'), function(i , e) {
			e.reset();
		});
	}
	
	//Global Navigation Effects
	$("ul", "#header").lavaLamp({
		fx: "easeOutBack",
		speed: 700,
		click: function() {
			//Toggles for client area and contact form
			var section = this.href.split('#')[1],
				$this = $('#' + section),
				h = $this.height() + parseInt($this.css('paddingTop')) + parseInt($this.css('paddingBottom'));
				
			if(section == 'login' || section == 'contact') {
				
				if(section == 'login' && $("#contact").is(":visible")) {
					toggler($('#contact'), 'toggle');
				} else if(section == 'contact' && $("#login").is(":visible")) {
					toggler($('#login'), 'toggle');
				}
				
				toggler($this, 'toggle');
				return false;
			}
		}
	});
	
	$('.cancel', '#sliders').live('click', function() {
		toggler($('#login, #contact'), 'hide');
		return false;
	});
	
	$('.forgot, .remembered').live('click', function() {
		$('#errors').slideUp('slow');
		$('.user_input', '#login').val('');
		$('h1', '#login form:eq(1)').text('If you have forgotten your password, you can reset it here.');
		if(this.className == "forgot") {
			$('form:eq(0)', '#login').hide();
			$('form:eq(1)', '#login').show();
		} else {
			$('form:eq(1)', '#login').hide();
			$('form:eq(0)', '#login').show();
		}
		return false;
	});
	
	$('form:eq(0)', '#login').submit(function() {
		var username = $('input[name="username"]', this).val(),
			password = $('input[name="password"]', this)[0].value;
		$.ajax({
			url: '/processes/login.php',
			data: { 'username': username, 'password': password },
			success: function(success) {
				success != 0 ? window.location = success : $('p', '#errors').text('Wrong Username and Password combination.').show().parent().slideDown('slow');
			}
		});
		return false;
	});
	
	$('form:eq(1)', '#login').submit(function() {
		var email = $('input[name="email"]', this)[0].value,
			validEmail = /^((([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);
		form = this;

		if(!validEmail) {
			$('p', '#errors').text('Enter a valid email address.').show().parent().slideDown('slow');
		} else {

			$.ajax({
				url: '/processes/reset-password.php',
				data: 'action=reset&email='+email,
				success: function(success) {
					if(success == 1) {
						$('p', '#errors').text('Thank you. Check your email to reset your password.').show().parent().slideDown();
						form.reset();
					} else {
						$('p', '#errors').text('No client account was found with the email address you entered.').show().parent().slideDown();
					}
				}
			});
		}
		return false;
	});
	
	$('#contact_form').validate({
		rules: {
			name: 'required',
			from: {
				required: true,
				email: true
			},
			message: 'required'
		},
		messages: {
			name: 'Name is required. ',
			from: {
				required: "Email is required. ",
				email: "Email needs to be valid. "
			},
			message: 'Message is required. '
		},
		errorElement: 'span',
		errorContainer: "#errors",
		errorLabelContainer: "#errors p",
		showErrors: function(eMap, eList) {
			for ( var i = 0; this.errorList[i]; i++ ) {
				var error = this.errorList[i];
				this.settings.highlight && this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass );
				this.showLabel( error.element, error.message );
			}
			if( this.errorList.length ) {
				this.toShow = this.toShow.add( this.containers );
			}
			if (this.settings.success) {
				for ( var i = 0; this.successList[i]; i++ ) {
					this.showLabel( this.successList[i] );
				}
			}
			if (this.settings.unhighlight) {
				for ( var i = 0, elements = this.validElements(); elements[i]; i++ ) {
					this.settings.unhighlight.call( this, elements[i], this.settings.errorClass, this.settings.validClass );
				}
			}
			this.toHide = this.toHide.not( this.toShow );
			for( var j = 0; j < this.toHide.length; j++ ) {
				this.toHide[j] != $( this.settings.errorContainer )[0] ? $(this.toHide[j]).hide() : $(this.toHide[j]).slideUp('fast');
			}
			
			//Only difference from this.defaultShowErrors is the slideDown effect for errors div
			this.toShow.not( this.settings.errorContainer ).show(); 
			if(this.toShow.length > 1) {
				$(this.settings.errorContainer).slideDown('slow');
			}
		},
		invalidHandler: function(form, validator) {
			$('p', '#errors').text('');
		},
		submitHandler: function(form) {
			var senderName = $('input[name="name"]', '#contact_form').val(),
				senderEmail = $('input[name="from"]', '#contact_form').val(),
				senderSubject = $('option:selected', '#contact_form').val(),
				senderMsg = $('textarea', '#contact_form').val();
				
			$.ajax({
				url: '/processes/contact.php',
				data: 'name='+senderName+'&from='+senderEmail+'&subject='+senderSubject+'&message='+senderMsg,
				type: "POST",
				success: function(data) {
					$('p', '#errors').text('Thank you. Your message has been sent.').show().parent().slideDown('slow');
					form.reset();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					$('p', '#errors').text('Please provide your name, message and a valid email address.').show().parent().slideDown('slow');
				}
			});
		}
	});
	
	//Global Hosting Dropdown
	$('span', '.hosting dt').not('a').toggle(function() {
		$('dl', '.hosting').addClass('over').animate({
			height: 182
		}, 'slow');
	}, function() {
		$('dl', '.hosting').animate({
			height: 38
		}, 'slow', function() {
			$(this).removeClass('over');
		});
	});
	
	//Global Footer popup
	$('a', '#footer .left').click(function() {
		var url = this.href;
		window.open(url, '_blank', 'width=770,height=430,scrollbars=no,toolbar=no,menubar=no,resizable=yes');
		return false;
	});
	
	//Change select dropdowns for styling
	$('select', '#contact, #packages').sSelect({ ddMaxHeight: 'auto' });
	
	//Homepage Scroller
	var dontSpazz = true;
	$('a', '#banner_nav').click(function() {
		var $this = this,
			clicked = $('a', '#banner_nav').index($(this, "#'#banner_nav'")),
			animation = function(options) {
				if(dontSpazz) {
					dontSpazz = false;
					$('ul:eq(0)', '#banner').animate(options, 700, 'easeOutQuart', function() {
						$('a', '#banner_nav').removeClass('on');
						$this.className = 'on';
						dontSpazz = true;
					});
				}
			};
			
		switch (clicked) {
			case 0:
				animation({
					'margin-left': 0,
					'margin-top': 0
				});
				break;
			case 1:
				animation({
					'margin-left': -1000,
					'margin-top': 0
				});
				break;
			case 2:
				animation({
					'margin-left': 0,
					'margin-top': -463
				});
				break;
			case 3:
				animation({
					'margin-left': -1000,
					'margin-top': -463
				});
				break;
			case 4:
				animation({
					'margin-left': 0,
					'margin-top': -926
				});
				break;
			default:
				animation({
					'margin-left': 0,
					'margin-top': 0
				});
				break;
		}
		return false;
	});
	
	//About pages with image carousel
	$('#image_popup').dialog($.extend(globalDialogOptions, {
		show: 'puff',
		width: 420,
		height: 313,
		dialogClass: 'image_only'
	}));
	
	$('.arrow').carousel({ cTarget: '#carousel ul', startPos: 0});
	$('img', '#carousel ul').live('click', function() {
		var largeImagePath = this.src.replace('thumbs', 'large');
		$('#image_popup').append('<img src="' + largeImagePath + '" alt="" />').dialog('open');
	});
	
	//Hosting Pages
	$('li[title]', '#offerings').tooltip({
		position: "center right",
		effect: 'fade',
		fadeInSpeed: 250,
		fadeOutSpeed: 50
	});
	
	//FAQ open - close
	var faqFlipper = 1;
	$('.open').click(function () {
		$('.questions').slideToggle('medium');
		if(faqFlipper == 1) {
			$('html,body').animate({scrollTop: $('#faq')[0].offsetTop}, 800);
			faqFlipper = 0;
		} else {
			$('html,body').animate({scrollTop: $('#content')[0].offsetTop}, 800);
			faqFlipper = 1;
		}
		return false;
	});
	$('.close').click(function () {
		$('.questions').slideToggle('medium');
		$('html,body').animate({scrollTop: $('#content')[0].offsetTop}, 800);
		faqFlipper = 1;
		return false;
	});
	
	//FAQ popup init
	$('#hosting_dialog').dialog($.extend(globalDialogOptions, {
		height: 'auto'
	}));
	//FAQ grab answers
	$('a', '#faq ol').click(function() {
		var qNum = parseInt($('a', '#faq ol').index($(this, '#faq ol'))),
			section = $(this).parents('ol')[0].className, group;
			
		$.getJSON('/hosting-data/_faq-json', function(data) {
			switch (section) {
				case 'web-hosting':
					group = data.webHosting;
					break;
				case 'reseller-hosting':
					group = data.resellerHosting;
					break;
				case 'vps-hosting':
					group = data.vpsHosting;
					break;
				case 'dedicated-server':
					group = data.dedicatedServer;
					break;
				default:
					group = data.webHosting;
					break;
			}
			$.each(group, function(i, e) {
				if(i == qNum) {
					$('<p />').html(e.a).appendTo('#hosting_dialog');
					$('#hosting_dialog').dialog({ title: e.q, width: 600, height: 'auto' }).dialog('open');
				}
			});
		});
		return false;
	});
	$('a', '#sign_up').click(function() {
		$('html,body').animate({scrollTop: $('#content')[0].offsetTop}, 500);
		return false;
	});
	
	//Dynamic dialog for demos and lists
	$('.demo', '#features').click(function() {
		var newPage = this.href,
			iframe = '<iframe src ="' + newPage + '" width="100%" height="500" frameborder="0" marginheight="0" marginwidth="0" name="demo" scrolling="auto" />',
			title = $('h3', $(this).parents('.feature_text')).text();
		$('#hosting_dialog').html(iframe).dialog({ title: title, width: 900, height: 'auto' }).dialog('open');
		return false;
	});
	$('.lists', '#features').click(function() {
		var section = this.href.split('#')[1];
		$.getJSON('/hosting-data/_lists-json', function(data) {
			switch(section) {
				case 'blog-portal-shopping-cart':
					section = data.blog_portal_shopping_cart;
					break;
				case 'linux-languages':
					section = data.linux_languages;
					break;
				case 'windows-languages':
					section = data.windows_languages;
					break;
				case 'linux-features':
					section = data.linux_features;
					break;
				case 'windows-features':
					section = data.windows_features;
					break;
				case 'one-click-install':
					section = data.one_click_install;
					break;
				default:
					break;
			}
			$('#hosting_dialog').dialog({ title: section.title, height: 500, width: 500 }).html(section.content).dialog('open');
		});
		return false;
	});
	
	//Hosting option select changes
	$('.operating_system').change(function() {
		var switchOS = function(ele, panel) {
			var os = ele.value.toLowerCase().replace(' ', '').split('-')[0];
			$('option:eq(' + ele.selectedIndex +')', '.operating_system').attr('selected', 'selected');
			$('.selectedTxt', $('.operating_system').next()).text(ele.value.replace(/ /g, '').split('-')[0]);
			$(".panel").text(panel);
			os == 'windows' ? $('#linux').hide() : $('#windows').hide();
			$('#'+os).show();
	
			//Changes all package Id's based on OS
			$.each($('option:selected', '.operating_system'), function(i, e) {
				var $container = $(e).parents('form');
				$('input[name="package_id"]', $container)[0].value = e.value.replace(/ /g, '').split('-')[1];
			});
		
		};
		this.selectedIndex == 0 ? switchOS(this, "cPanel 11.x") : switchOS(this, "Plesk 9.x");
	});
	//Reseller + VPS Hosting page - offer changes depending on OS
	$('select[name="os"]', '.reseller-hosting, .vps-hosting').change(function() {
		if(this.selectedIndex == 1) {
			$('.linux_offer').hide();
			$('.windows_offer').show();
		} else { 
			$('.linux_offer').show();
			$('.windows_offer').hide();
		}
	});
	//Dedicated Hosting page only
	$('select', ".package_dedicated").change(function() {
		var cid = $(this).find("option").eq(this.selectedIndex).attr("class");
		switch(this.name) {
			case 'processor':
				$("input[name$='processor_cid']").val(cid);
				$('li', '.memory').show();
				switch(this.selectedIndex) {
					case 0:
						$('.cpu').text('2.80 GHz');
						$('.speed').text('3 MB');
						$('li:eq(4), li:eq(5), li:eq(6)', '.memory').hide();
						break;
					case 1:
						$('.cpu').text('2.50 GHz');
						$('.speed').text('4 MB');
						$('li:eq(5), li:eq(6)', '.memory').hide();
						break;
					case 2:
						$('.cpu').text('2.13 GHz, 4.80 GT/s Intel QP');
						$('.speed').text('4 MB');
						break;
					case 3:
						$('.cpu').text('2.13 GHz, 4.80 GT/s Intel QP');
						$('.speed').text('4 MB');
						break;
					default:
						$('.cpu').text('2.80 GHz');
						$('.speed').text('3 MB');
						$('li:eq(4), li:eq(5), li:eq(6)', '.memory').hide();
						break;
				}
				$('option:eq(0)', '.memory').attr('selected', 'selected');
				$('.memory').change();
				break;
			case 'hard_drive':
				$("input[name$='hard_drive_cid']").val(cid);
				$('li', ".raid").show();
				if(this.selectedIndex == 0 || this.selectedIndex == 2 || this.selectedIndex == 4 || this.selectedIndex == 6) {
					$('li:eq(1)', ".raid").hide();
				}
				//Resets changed dropdowns
				$('option:eq(0)', '.raid').attr('selected', 'selected');
				$('.raid').change();
				//End reset
				break;
			case 'memory':
				$("input[name$='memory_cid']").val(cid);
				$('li', ".bandwidth").show();
				if(this.selectedIndex == 0 || $(".processor")[0].selectedIndex == 0) {
					$('li:eq(2)', ".bandwidth").hide();
				}
				//Resets changed dropdowns
				$('option:eq(0)', '.bandwidth').attr('selected', 'selected');
				$('.bandwidth').change();
				//End reset
				break;
			case 'raid':
				$("input[name$='raid_cid']").val(cid);
				break;
			case 'os':
				$("input[name$='os_cid']").val(cid);
				$('li', ".control_panel").show();
				if(this.selectedIndex == 8 || this.selectedIndex == 9 || this.selectedIndex == 10) {
					$('li:eq(1)', ".control_panel").hide();
				} else if(this.selectedIndex == 2 || this.selectedIndex == 3 || this.selectedIndex == 4 || this.selectedIndex == 5 || this.selectedIndex == 6 || this.selectedIndex == 7) {
					$('li:eq(1), li:eq(2), li:eq(3)', ".control_panel").hide();
				}
				//Resets changed dropdowns
				$('option:eq(0)', '.control_panel').attr('selected', 'selected');
				$('.control_panel').change();
				//End reset
				break;
			case 'control_panel':
				$("input[name$='control_panel_cid']").val(cid);
				$('li', '.bandwidth').show();
				switch(this.selectedIndex) {
					case 0:
						$('li:eq(2)', ".bandwidth").hide();
						break;
					case 1:
						if($(".memory")[0].selectedIndex == 0) {
							$('li:eq(2)', ".bandwidth").hide();
						}
						break;
					case 2:
						if($(".memory")[0].selectedIndex == 0) {
							$('li:eq(2)', ".bandwidth").hide();
						}
						break;
					case 3:
						if($(".memory")[0].selectedIndex == 0) {
							$('li:eq(2)', ".bandwidth").hide();
						}
						break;
					default:
						break;
				}
				//Resets changed dropdowns
				//$('option:eq(0)', '.memory, .bandwidth').attr('selected', 'selected');
				$('option:eq(0)', '.bandwidth').attr('selected', 'selected');
				$('.bandwidth').change();
				//End reset
				break;
			case 'bandwidth':
				$("input[name$='bandwidth_cid']").val(cid);
				break;
			default:
				break;
		}
		calcPrice($('option:selected', ".package_dedicated"), $('.total_price'));
	});
	//VPS Hosting page only
	$('select', '.vps-hosting').change(function() {
		var changePrice = function(added) {
			$.each($('.total_price, h3 span', '#packages'), function(i ,e) {
				var aggregated = parseInt($('input[name="base_price"]', $(e).parents('div:eq(0)'))[0].value) + added;
				e.type == "text" ? e.value = '$' + aggregated : $(e).text('$' + aggregated);
			});
		};
		if(this.name == 'os') {
			switch(this.selectedIndex) {
				case 0:
					$('li', '.vps_panel').show();
					changePrice(0);
					break;
				case 1:
					$('li:eq(1)', '.vps_panel').hide();
					changePrice(15);
					break;
				default:
					$('li', '.vps_panel').show();
					changePrice(0);
					break;
			}
			$('option:eq(0)', '.vps_panel').attr('selected', 'selected');
			$('.vps_panel').change();
		} else {
			var cid = $(this).find("option").eq(this.selectedIndex).attr("class");
			$("input[name$='control_panel_cid']").val(cid);
			var $parent = $(this).parents('div:eq(0)'),
				basePrice = $('select[name="os"]', $parent)[0].selectedIndex == 1 ? parseInt($('input[name="base_price"]', $parent)[0].value) + 15 : parseInt($('input[name="base_price"]', $parent)[0].value),
				totalPrice = basePrice + parseInt($('option:selected', this).attr('label').replace(' ', '').split(',')[0]);
			$('.total_price', $parent)[0].value = '$' + totalPrice;
			$('h3 span', $parent).text('$' + totalPrice);
		}
	});
	
});
