Ext.namespace('cc.re.oc.client');
Ext.namespace('cc.re.oc.products');

cc.re.oc.client.logged_in = false;

/**
* Shows the login window
*/
cc.re.oc.client.show_login = function()
{
	cc.re.oc.client.login_win.show();
}


/**
* Submits the user login
*/
cc.re.oc.client.login = function(form)
{
	if (!form)
	{
		form = 'oc_login_form';
	}
	
	var sf = Jsui.getForm(form);
	sf.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=do_login'
	});

	fields = sf.getValues();

	// Validate the values
	if (fields.email == '' || fields.password == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter both your email and your password to log in.'
		);
		return false;
	}

	sf.submit({
		success: function(form, action)
		{
			Jsui.messagebox(
				'Login Successful',
				'You have sucessfully logged in.  This page will now refresh to give you access to all client features.'
			);
			
			if (cc.re.oc.client.login_win)
			{
				cc.re.oc.client.login_win.hide();
			}
			
			setTimeout(function(){
				document.location.reload();
			}, 2000);

		},
		failure: function(response, opt, data)
		{
			if (data && data.error)
			{
				Jsui.messagebox('Error!', '' + data.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
			}
		}
	});
	return true;
}


/**
* Logs the user out
*/
cc.re.oc.client.logout = function()
{
	Jsui.confirm('Logout?', 'Are you sure you want to log out?', function(btn) {
		if (btn == 'yes')
		{
			Ext.Ajax.request({
				url: 'admin/modules/order_center/site_provider.php?act=do_logout',
				'method': 'GET',
				success: function(response, options) {
					Jsui.messagebox('Logout', 'Logout successful!');
					document.location.reload();
				},
				failure: function(response, options) {
					Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
				}
			});
		}
	});
}


/**
* Shows the recover window
*/
cc.re.oc.client.show_recover = function()
{
	cc.re.oc.client.login_win.hide();
	cc.re.oc.client.pw_recover_win.show();
}

/**
* Submits the recover password form
*/
cc.re.oc.client.recover = function()
{
	var sf = Jsui.getForm('oc_recover_form');
	sf.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=recover'
	});

	fields = sf.getValues();
	// Validate the values
	if (fields.email == '')
	{
		Jsui.messagebox('Missing Email', 'You must enter your email address to receive your password!');
		return false;
	}

	sf.submit({
		success: function(request, options, data)
		{
			if (data.success)
			{
				Jsui.messagebox(
					'Password Sent',
					'Your password has been sent to your email.  If you have not received your password in a few minutes, check your spam folder.'
				);
				cc.re.oc.client.pw_recover_win.hide();
			}
			else
			{
				if (data && data.error)
				{
					Jsui.messagebox('Error!', '' + data.error);
				}
				else
				{
					Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server. (1)');
				}
			}
		},
		failure: function(response, opt, data)
		{
			if (data && data.error)
			{
				Jsui.messagebox('Error!', '' + data.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server. (2)');
			}
		}
	});
	return true;
}




/**
* Sends the user registration
*/
cc.re.oc.client.submit_registration = function()
{
	var sf = new Ext.form.BasicForm('oc_register_form', {
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=register'
	});

	fields = sf.getValues();

	// Validate the values
	var errors = '';
	var error_count = 0;
	if (fields.name == '')
	{
		errors += "You must enter a name.<br/>";
		error_count++;
	}
	if (fields.email == '')
	{
		errors += "You must enter a valid email address.<br/>";
		error_count++;
	}
	if (fields.password == '')
	{
		errors += "You must choose a password.<br/>";
		error_count++;
	}
	if (fields.password_confirm != fields.password)
	{
		errors += "The password and password confirmation must be the same.<br/>";
		error_count++;
	}

	if (error_count > 0)
	{
		Jsui.messagebox('Incomplete Data',
			'The following error' + (error_count > 1 ? 's were' : 'was') + ' found in your registration:<br/><br/>' + errors + '<br/>Please correct these errors and click `Register` again!'
		);
		return false;
	}

	sf.submit({
		success: function(form, action)
		{
			Jsui.messagebox(
				'Registration Successful',
				'Thank you for registering!<br/>Your member account has been sucessfully created.  You can now log in using your email and the password you have chosen.'
			);
			cc.re.oc.client.register_win.hide();
		},
		failure: function(form, action)
		{
			if (action.result.error)
			{
				Jsui.messagebox('Error!', '' + action.result.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
			}
		}
	});
	return true;
}





/**
* Displays the item details
*/
cc.re.oc.products.shown_cpl_item = 0;
cc.re.oc.products.show_cpl_item_details = function(id)
{
	if (cc.re.oc.products.shown_cpl_item != -1)
	{
		// Hide previous item
		Ext.get('oc_cpl_' + cc.re.oc.products.shown_cpl_item).setStyle({display: 'none'});
	}

	var el = Ext.get('oc_cpl_' + id);
	if (el)
	{
		el.setStyle({display: 'block'});
		cc.re.oc.products.shown_cpl_item = id;
	}
	else
	{
		alert('Missing element oc_cpl_' + id);
	}
}



/**
* Adds a product to order
*
* @param id {string} Form ID
*/
cc.re.oc.products.add_to_order = function(id)
{
	// Alert user they need to login first if needed
	if (!cc.re.oc.client.logged_in)
	{
		Jsui.messagebox('Error', 'You must login before adding items to your order!');
		return;
	}

	var f = Jsui.getForm(id);

	var vals = f.getValues();

	// Check if there is at least one quantity entered
	this.empty = true;
	Jsui.iterate(vals, function(name, val) {
		if (val != '')
		{
			this.empty = false;
			return false;
		}

		return true;
	}, this);

	if (this.empty)
	{
		Jsui.messagebox('Error', 'Enter the quantity you want to order!');
		return;
	}

	f.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=add_to_cart'
	});

	f.submit({
		success: function(response, opt, data)
		{
			if (data.success === true)
			{
				Jsui.messagebox('Add to cart', data.msg + '');
			}
			else if (data.msg)
			{
				Jsui.messagebox('Error', data.msg + '');
			}
			else
			{
				Jsui.messagebox('Error', 'An error was encountered while adding the item to your order');
			}
		},
		failure: function(response, opt, data)
		{
			Jsui.messagebox('Error', 'An error was encountered while adding the item to your order');
		}
	});
}




/**
* Starts registration
*/
cc.re.oc.client.register_step2 = function(is_business)
{
	Ext.get('oc_register_page_1').setStyle({display: 'none'});
	if (is_business)
	{
		//alert('test');
		Ext.get('oc_register_page_2b').setStyle({display: 'block'});
		Ext.get('oc_register_page_2b').setStyle({visibility: 'visible'});
		
		Ext.get('oc_register_page_2p').setStyle({display: 'none'});
		Ext.get('oc_register_page_2p').setStyle({visibility: 'hidden'});
	}
	else
	{
		Ext.get('oc_register_page_2p').setStyle({display: 'block'});
		Ext.get('oc_register_page_2p').setStyle({visibility: 'visible'});
		
		Ext.get('oc_register_page_2b').setStyle({display: 'none'});
		Ext.get('oc_register_page_2b').setStyle({visibility: 'hidden'});
	}
}

/**
* Cancel client registration
*/
cc.re.oc.client.register_cancel = function()
{
	Jsui.confirm(
		'Cancel Registration?',
		'Are you sure you wish to cancel?  All entered data will be lost.  A registered client account is required to create any orders.',
		function(btn)
		{
			if (btn == 'yes')
			{
				window.location = 'home/';
			}
		}
	);
}

/**
* Password has changed
*/
cc.re.oc.client.password_changed = function(mode)
{
	var p1 = Ext.get('oc_register_2' + mode + '_p1').getValue();
	var p2 = Ext.get('oc_register_2' + mode + '_p2').getValue();

	//alert(p1 + ' | ' + p2);
	if (p1 == '')
	{
		Ext.get('oc_register_2' + mode + '_p1_e').setStyle({visibility: 'visible'});
	}
	else
	{
		Ext.get('oc_register_2' + mode + '_p1_e').setStyle({visibility: 'hidden'});
	}

	if (p1 == p2)
	{
		Ext.get('oc_register_2' + mode + '_p2_e').setStyle({visibility: 'hidden'});
	}
	else
	{
		Ext.get('oc_register_2' + mode + '_p2_e').setStyle({visibility: 'visible'});
	}
}


/**
* Country has changed
*
* @param mode {char} b (business) or p (private)
*/
cc.re.oc.client.country_changed = function(mode)
{
	var new_ctry = Ext.get('oc_register_2' + mode + '_ctry').getValue();

	Ext.get('oc_register_2' + mode + '_currency').dom.value = cc.utils.get_currency(new_ctry);

	if (new_ctry == 'CA')
	{
		Ext.get('oc_register_2' + mode + '_label_prov').dom.innerHTML = 'Province';
		Ext.get('oc_register_2' + mode + '_label_pc').dom.innerHTML = 'Postal Code';

		// Show/hide the province
		Ext.get('oc_register_2' + mode + '_state_CA').setStyle({display: 'block'});
		Ext.get('oc_register_2' + mode + '_state_US').setStyle({display: 'none'});
		Ext.get('oc_register_2' + mode + '_state').setStyle({display: 'none'});
	}
	else if (new_ctry == 'US')
	{
		Ext.get('oc_register_2' + mode + '_label_prov').dom.innerHTML = 'State';
		Ext.get('oc_register_2' + mode + '_label_pc').dom.innerHTML = 'ZIP';

		// Show/hide the province
		Ext.get('oc_register_2' + mode + '_state_CA').setStyle({display: 'none'});
		Ext.get('oc_register_2' + mode + '_state_US').setStyle({display: 'block'});
		Ext.get('oc_register_2' + mode + '_state').setStyle({display: 'none'});
	}
	else
	{
		Ext.get('oc_register_2' + mode + '_label_prov').dom.innerHTML = 'Province';
		Ext.get('oc_register_2' + mode + '_label_pc').dom.innerHTML = 'Postal Code';

		// Show/hide the province
		Ext.get('oc_register_2' + mode + '_state_CA').setStyle({display: 'none'});
		Ext.get('oc_register_2' + mode + '_state_US').setStyle({display: 'none'});
		Ext.get('oc_register_2' + mode + '_state').setStyle({display: 'block'});
	}
}

/**
* Submit registration
*
* @param mode {char} b (business) or p (private)
*/
cc.re.oc.client.register_submit = function(mode)
{
	var sf = Jsui.getForm('oc_register_2' + mode);
	sf.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=register'
	});

	fields = sf.getValues();
	//console.dir(fields);

	// Validate the values
	if (fields['register[client][email]'] == '')
	{
		Jsui.messagebox('Login Error',
			'A valid email is <b>required</b> to open an account.'
		);
		return false;
	}
	if (!Jsui.Validation.validate_email(fields['register[client][email]']))
	{
		Jsui.messagebox('Login Error',
			'The email address entered does not appear to be valid.'
		);
		return false;
	}

	if (fields['register[client][password]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter a password to create an account.'
		);
		return false;
	}
	if (fields['register[client][password]'] != fields['password2'])
	{
		Jsui.messagebox('Login Error',
			'The password confirmation does not match the password entered.'
		);
		return false;
	}

	if (fields['register[client][name]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'name to create an account.'
		);
		return false;
	}
	if (fields['register[client][address]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'address to create an account.'
		);
		return false;
	}
	if (fields['register[client][city]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'city to create an account.'
		);
		return false;
	}
	/*if (fields['register[client][country]'] != 'CA' && fields['register[client][country]'] != 'US' && fields['register[client][province]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'province to create an account.'
		);
		return false;
	}*/
	if (fields['register[client][postal_code]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'postal code to create an account.'
		);
		return false;
	}

	if (fields['register[client][phone]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'phone number to create an account.'
		);
		return false;
	}

	// CONTACT
	if (mode == 'b' && fields['register[contact][name]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter a contact name to create an account.'
		);
		return false;
	}

	sf.submit({
		success: function(request, options, data)
		{
			if (data.success)
			{
				Jsui.messagebox(
					'Success',
					'' + data.msg,
					function() {
						document.location = 'home/';
					}
				);
			}
			else
			{
				if (data && data.error)
				{
					Jsui.messagebox('Error!', '' + data.error);
				}
				else
				{
					Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
				}
			}
		},
		failure: function(response, opt, data)
		{
			if (data && data.error)
			{
				Jsui.messagebox('Error!', '' + data.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
			}
		}
	});
	return true;
}


/**
*
*
*
* ORDER (CART)
*
*
*/

/**
* Update order
*
*/
cc.re.oc.client.update_order = function()
{
	var f = Ext.get('oc_cart_form');
	
	var sf = Jsui.getForm('oc_cart_form');
	var vals = sf.getValues();
	
	Ext.Ajax.request({
		url: 'admin/modules/order_center/site_provider.php?act=update_order',
		params: vals,
		method: 'POST',
		callback: function(opt, success, response) {
			// Failed request
			if (!success)
			{
				Jsui.messagebox('Error', 'A connection error was encountered while attempting to remove the item from the order.');
				return;
			}
			
			// Success
			Ext.get('oc_view_cart_container').dom.innerHTML = response.responseText;
		}
	});
}

/**
* Update order
*
*/
cc.re.oc.client.clear_order = function()
{
	Jsui.confirm(
		'Clear Order',
		'Are you sure you wish to <b>remove ALL items</b> from your order?',
		function (btn) {
			if (btn == 'yes')
			{
				var f = Ext.get('oc_cart_form');

				// Non-ajax
				f.dom.action = 'admin/modules/order_center/site_provider.php?act=clear_order';
				f.dom.submit();
			}
		}
	);
}


/**
* Submits an order for completion
*
*/
cc.re.oc.client.finish_checkout = function()
{
	var f = Ext.get('oc_checkout_form');

	// Non-ajax
	f.dom.action = 'admin/modules/order_center/site_provider.php?act=finalize_order';
	f.dom.submit();
}



/**
* Removes all of an item from an order
*
* @param id {int} The order_details ID
* 
*/
cc.re.oc.client.rem_from_order = function(id)
{
	Jsui.confirm('Remove item?', 'Are you sure you want to remove this item from the order?', function(btn) {
		if (btn == 'yes')
		{
			var f = Ext.get('oc_cart_form');
			
			// Ajax replace element content
			f.dom.action = '&odid=' + id;
			Ext.Ajax.request({
				url: 'admin/modules/order_center/site_provider.php?act=remove_item',
				params: {
					odid: id
				},
				method: 'POST',
				callback: function(opt, success, response) {
					// Failed request
					if (!success)
					{
						Jsui.messagebox('Error', 'A connection error was encountered while attempting to remove the item from the order.');
						return;
					}
					
					// Success
					Ext.get('oc_view_cart_container').dom.innerHTML = response.responseText;
				}
			});
		}
	});
}



/**
* Change the password
*/
cc.re.oc.client.change_pw_submit = function()
{
	var sf = Jsui.getForm('oc_change_password_form');
	sf.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=change_pw'
	});

	fields = sf.getValues();

	// Validate the values
	var errors = '';
	var error_count = 0;
	if (fields.current == '')
	{
		errors += "You must enter the current password.<br/>";
		error_count++;
	}
	if (fields.new_pw == '')
	{
		errors += "You must enter a new password.<br/>";
		error_count++;
	}
	if (fields.new_pw != fields.new_pw2)
	{
		errors += "The new password and new password confirmation must be the same.<br/>";
		error_count++;
	}
	if (fields.current == fields.new_pw)
	{
		errors += "The new password cannot be the same as the old password.<br/>";
		error_count++;
	}

	if (error_count > 0)
	{
		Jsui.messagebox('Error',
			'The following error' + (error_count > 1 ? 's were' : 'was') + ' found in your change password form:<br/><br/>' + errors + '<br/>Please correct these errors and try again!'
		);
		return false;
	}

	sf.submit({
		success: function(form, action, data)
		{
			Jsui.messagebox(
				'Password Change Successful',
				'Your password has been sucessfully changed.'
			);
			
			sf.dom.reset();
		},
		failure: function(form, action, data)
		{
			if (data.error)
			{
				Jsui.messagebox('Error!', '' + data.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
			}
		}
	});
	return true;
}




/**
* Submit edit account
*
* @param mode {char} b (business) or p (private)
*/
cc.re.oc.client.edit_submit = function(mode)
{
	var sf = Jsui.getForm('oc_register_2' + mode);
	sf.configure({
		method: 'POST',
		url: 'admin/modules/order_center/site_provider.php?act=update_account'
	});

	fields = sf.getValues();
	//console.dir(fields);

	// Validate the values
	if (fields['register[client][email]'] == '')
	{
		Jsui.messagebox('Error',
			'A valid email is <b>required</b> for every account.'
		);
		return false;
	}
	if (!Jsui.Validation.validate_email(fields['register[client][email]']))
	{
		Jsui.messagebox('Error',
			'The email address entered does not appear to be valid.'
		);
		return false;
	}

	if (fields['register[client][name]'] == '')
	{
		Jsui.messagebox('Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'name.'
		);
		return false;
	}
	if (fields['register[client][address]'] == '')
	{
		Jsui.messagebox('Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'address.'
		);
		return false;
	}
	if (fields['register[client][city]'] == '')
	{
		Jsui.messagebox('Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'city.'
		);
		return false;
	}
	/*if (fields['register[client][country]'] != 'CA' && fields['register[client][country]'] != 'US' && fields['register[client][province]'] == '')
	{
		Jsui.messagebox('Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'province.'
		);
		return false;
	}*/
	if (fields['register[client][postal_code]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'postal code.'
		);
		return false;
	}

	if (fields['register[client][phone]'] == '')
	{
		Jsui.messagebox('Login Error',
			'You must enter your ' + (mode == 'b' ? "company's " : '') + 'phone number.'
		);
		return false;
	}

	sf.submit({
		success: function(request, options, data)
		{
			if (data.success)
			{
				Jsui.messagebox(
					'Success',
					'' + data.msg,
					function() {
						
					}
				);
			}
			else
			{
				if (data && data.error)
				{
					Jsui.messagebox('Error!', '' + data.error);
				}
				else
				{
					Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
				}
			}
		},
		failure: function(response, opt, data)
		{
			if (data && data.error)
			{
				Jsui.messagebox('Error!', '' + data.error);
			}
			else
			{
				Jsui.messagebox('Connection error!', 'An error was encountered while communicating with the server.');
			}
		}
	});
	return true;
}


/**
* Init
*/
Ext.onReady(function(){
	/**
	* The login window
	*/
	cc.re.oc.client.login_win = new Jsui.Window({
		title: 'Login to your account',
		width: 280,
		autoHeight: true,

		bodyStyle: 'padding: 25px;',
		closable: true,
		closeAction: 'hide',
		constrain: true,
		draggable: true,
		hideModel: 'display',
		layout: 'fit',
		modal: true,
		resizable: false,

		html: "\
			<form id='oc_login_form'>\
				<div class='label'>Email:</div>\
				<div class='field'><input type='text' name='email' /></div>\
				<div class='label'>Password:</div>\
				<div class='field'><input type='password' name='password' /></div>\
				<div class='label'>Keep me logged in: <input type='checkbox' name='remember' value='yes' /></div>\
			</form>\
		"
	});

	var btn = new Jsui.Button({
		text: 'Login',
		appendTo: cc.re.oc.client.login_win.el.child('div.jsui-window-footer-container'),
		handler: function(e, t, o) {
			cc.re.oc.client.login();
		}
	});

	cc.re.oc.client.login_win.el.child('div.jsui-window-footer-container').insertHtml('afterBegin', '<a href="#" onclick="cc.re.oc.client.show_recover(); return false;" />Forgot Password?</a>', true);


	/**
	* The pw recovery window
	*/
	cc.re.oc.client.pw_recover_win = new Jsui.Window({
		title: 'Password Recovery',
		width: 280,
		autoHeight: true,

		bodyStyle: 'padding: 25px;',
		closable: true,
		closeAction: 'hide',
		constrain: true,
		draggable: true,
		hideModel: 'display',
		layout: 'fit',
		modal: true,
		resizable: false,

		html: "\
			<form id='oc_recover_form'>\
				<table>\
					<tr>\
						<td class='buttons' colspan='2'>Enter your email below and click Recover Password.  Your password will be sent to your email address.</td>\
					</tr>\
					<tr>\
						<td>\
							<div class='label'>Email:</div>\
							<div class='field'><input type='text' name='email' /></div>\
						</td>\
					</tr>\
				</table>\
			</form>\
		"
	});

	var btn2 = new Jsui.Button({
		text: 'Recover Password',
		appendTo: cc.re.oc.client.pw_recover_win.el.child('div.jsui-window-footer-container'),
		size: 'medlarge',
		handler: function(e, t, o) {
			cc.re.oc.client.recover();
		}
	});
});