/* suite.html */
var initialize_quantity_listeners = function(key) {
	if($('#' + key + 'method').val() != ''){adjust_quantity(key);}
	$('#' + key + 'method').change(function(){adjust_quantity($(this).attr('id').replace('method', ''));});
	$('form#' + key + 'form').submit(function(){return validate_suite_form($(this).attr('id').replace('form', ''));});
	return;
}

var adjust_quantity = function(key) {
	var quantity = key + 'quantity';
	$('#' + quantity).removeOption(/./);
	$('#' + key + 'aquantity' + ' .' + $('#' + key + 'method').val()).each(
		function() {
			$('#' + quantity).append(
				$(document.createElement('option')).attr('value',$(this).val()).text($(this).html()));
			}
		);
	$('#' + quantity).change(function( objEvent ){ populate_sales_text(this.name,this.id); });
	$('#' + quantity).val('');
	return true;
}

var validate_suite_form = function(type) {
	var pass = true;
	var message = '';
	var method_border = '#999999';
	var quantity_border = '#999999';
	$('div.error').html('');
	if($('#' + type + 'method').val() == '') {
		pass = false;
		message += 'Please select a print method for the ' + type + '.<br />';
		method_border = '#F58B69';
	}
	if($('#' + type + 'quantity').val() == '' || $('#' + type + 'quantity').val() == '-') {
		pass = false;
		message += 'Please select a quantity for the ' + type + '.<br /><br />';
		quantity_border = '#F58B69';
	}
	$('select.pmethod').css('border', '1px solid #999999');
	$('select.pquantity').css('border', '1px solid #999999');
	if(message != '') {
		message = '<b>You have errors in your form:</b><br />' + message;
	}
	$('#' + type + 'error').html(message);
	$('#' + type + 'method').css('border', '1px solid ' + method_border);
	$('#' + type + 'quantity').css('border', '1px solid ' + quantity_border);
	return pass;
}

/* customize.html */
var change_swatches = function(swatch) {
	$('p#swatch_colors img').css('border', '2px solid white');
	$('input#body_color').val($('#' + swatch).attr('class'));
	$('#' + swatch).css('border', '2px solid black');
}
var validate_customize_form = function() {
	var pass = true;
	var message = '';
	var swatch_border = '#FFFFFF';
	var motif_font_border = '#999999';
	if($('input#body_color').length && $('input#body_color').val() == '') {
		pass = false;
		message += 'Please select a body text color.<br />';
		swatch_border = '#F58B69';
	}
	if($('select#motif_font').length && $('select#motif_font').val() == '') {
		pass = false;
		message += 'Please select a motif.<br />';
		motif_font_border = '#F58B69';
	}
	$('p#swatch_colors img').css('border', '2px solid ' + swatch_border);
	$('select#motif_font').css('border', '1px solid ' + motif_font_border);
	if(message != '') { 
		$('html,body').attr({scrollTop: 0});
		$('div#customize_error').html('<b>You have errors in your form:</b><br />' + message + '<br />');
	}
	if($('input#body_color').val() != '') {
		$('p#swatch_colors img.' + $('input#body_color').val()).css('border', '2px solid black');
	}
	return pass;
}
var retrieve_lost_password = function() {
    var args = 'email=' + $('#lost_password_email').val();
    $.get("/cgi-bin/paper/query/get_password.html", args, function(data) {
        var success = data.split(':')[0];
        if ( success == '1') {
            $('div#password').hide();
            $('div#return_messages').show();
            $('#return_messages').html(data.split(':')[1]);
        } else {
            $('table#password_error tr td').html(data.split(':')[1]);
            $('table#password_error').show();
        }
    });
    return false;
} 
var prepare_save_for_later = function() {
	if(validate_customize_form()) {
		if($('#logged_in').val() > 0) {
			personalize_save_for_later();
		} else {
			show_login_box();
		}
	}
	return false;
};

var show_login_box = function() { 
	$('div#create, div#password, div#return_values, table#login_error, table#create_error').hide();
	$('#login').show();
    $('input#login_where_from').val('save');
	show('jquery-loginbox');
};

var create_account = function() {
	var args = 'mv_username=' + $('#login_create').val() + '&mv_password=' + $('#password_create').val() + '&mv_verify=' + $('#confirm_password').val() + '&account_type=create';
	return login_or_create(args, 'create');
}
var switch_to_create = function() {
	$('div#login,div#password').hide();
	$('div#create').show();
	return false;
}
var login = function() {
	$('#account_type').val('login');
	var args = 'mv_username=' + $('#login_login').val() + '&mv_password=' + $('#password_login').val() + '&account_type=login';
	
	if( $('#display_once').val() ) {
		args = args + '&display_once=' + $('#display_once').val();
	}

	return login_or_create(args, 'login');
}
var login_or_create = function(args, error_box) {
	$.get($('#login_or_create').attr('action'), args, function(data) {
		var success = data.split(':')[0];
		if(success == '1') {
            if($('input#login_where_from').val() == 'save') {
				$('#logged_in').val(1);
			    if($('input#save_for_later').val() == '1') {
			    	personalize_save_for_later();
                    $('li#signin_li').hide();
                    $('li#logout_li').show();
                    $('li#myaccount_li').show();
                } else if ( $('#w2p_login').length > 0 ) { 
					webtoprint_save_for_later(); 
                    $('li#signin_li').hide();
                    $('li#logout_li').show();
                    $('li#myaccount_li').show();
					logged_in = 1;
                    hide('jquery-loginbox');
			    } else {
			    	$('#customize').submit();
			    }
            }
			cmCreatePageviewTag('ACCOUNT : SAVE ITEM : ' + error_box, $('input#code').val(), null);
            if ($('input#login_where_from').val() == 'login') {
				var special_location = $('#special_location').val();
				if(special_location == 'basket' || special_location == 'checkout') {
					var now = new Date();
					window.opener.location.href = basket_location + '?reload=' + now.getTime();
					self.close();
					return false;
				}
				$('li#signin_li',window.opener.document).hide();
				$('li#signin_save',window.opener.document).hide();
				$('li#logout_li',window.opener.document).show();
				$('li#myaccount_li',window.opener.document).show();
                $('#logged_in').val(1);
				self.close();
            }
		} else {
			$('table#' + error_box + '_error tr td').html(data.split(':')[1]);
			$('table#' + error_box + '_error').show();
			return false;
		}
	});
	return false;
}
var logout = function() {
    var args = '';
    var url_sections = new Array();
    var url = window.location.pathname;
    url_sections = url.split("/");
    $.get(logout_location, args, function(data) {
		if($('form#cart_contents').length || $('form#checkout').length) {
			var now = new Date();
			window.location.href = basket_location + '?reload=' + now.getTime();
		}
    	if ( url_sections[url_sections.length-1] == "customerservice.html" ||
        	url_sections[url_sections.length-1] == "account.html" ||
        	url_sections[url_sections.length-1] == "optin.html" ||
        	url_sections[url_sections.length-1] == "check_orders.html" ||
        	url_sections[url_sections.length-1] == "change_password.html" ||
        	url_sections[url_sections.length-1] == "saved_projects.html" ||
        	url_sections[url_sections.length-1] == "return.html" ||
			url_sections[url_sections.length-1] == "order_detail.html" 
    	) {
        	window.location.replace("/cgi-bin/paper/index.html");
    	}
    	$('li#signin_li,li#login_to_save').show();
    	$('li#logout_li,li#myaccount_li').hide();
    	$('#logged_in').val(0);
		logged_out = 0;
    });
    return false;
}

/* terms.html */
var validate_terms_form = function() {
	if($('input#terms_conditions').attr('checked')) {
		return true;
	} else {
		$('div#terms_error').html('You must check the box below.');
		return false;
	}
}

/* page load */
$(function() {
	/* suite.html */
	$('div#personalize_product_info h4:first').css('border-top', 'none').css('padding-top', '10px');
	$('input.ctype').each (function(){initialize_quantity_listeners($(this).val());});
	
	/* suite.html, customize.html */
	$('img.image_swatches').each(
		function() {
			$(this).mouseover(function() {$('img.personalize_product_img').attr({ src: '/personalized/' + $(this).attr('id') + '.jpg' });});
			$(this).mouseout(function() {$('img.personalize_product_img').attr({ src: '/personalized/' + $('img.personalize_product_img').attr('id') + '.jpg' });});
			$(this).click(function() { $('img.personalize_product_img').attr('id', $(this).attr('id')); $('img.personalize_product_image').attr({ src: '/personalized/' + $(this).attr('id') + '.jpg' });});
		}
	);
	$('a#show_terms').click(function() { return show('terms_and_conditions'); });
	$('a#hide_terms').click(function() { return hide('terms_and_conditions'); });
	$('a#show_learn').click(function() { return show('learn_more'); });
	$('a#hide_learn').click(function() { return hide('learn_more'); });

	/* customize.html */
	$('input#continue').click(function() {
		$('input#save_for_later').val('0');
		return validate_customize_form(); 
	});
	$('input#save_for_later_p').click(function() {
		$('input#save_for_later').val('1'); 
		return prepare_save_for_later();
	});
	$('li#signin_li').click(function() {
		return prepare_login();
	});
	$('li#logout_li').click(function() {
		return logout();
	});
	if($('p#swatch_colors img').length) {
		$('p#swatch_colors img').each(
			function() { $(this).click( function() { change_swatches($(this).attr('id')); } ); }
		);
		if($('input#body_color').val() != '') {
			$('p#swatch_colors img.' + $('input#body_color').val()).css('border', '2px solid black');
		}
	}
	$('p.monoline:last input').css('margin-bottom', '20px');
	$('input#submit_login').click(function() { return login(); });
	$('input#create_account').click(function() { return switch_to_create(); });
	$('input#submit_create').click(function() { return create_account(); });
	$('input#submit_password').click(function() { return retrieve_lost_password(); });

	/* terms.html */
	$('form#terms').submit(function(){return validate_terms_form();});

	/* upsell.html */
	$('img.add_button').click(function(){buyItem($(this).attr('id'));});
});

/* upsell.html */
var buyItem = function(sku) {
	var qty = parseInt($('input#qty_' + sku).val()) || 0;
	var pkg_qty = parseInt($('input#base_qty_' + sku).val()) || 0;
	$('div#error_' + sku).html('');
	$('span#msg_' + sku).html('');
	if(!qty) {
		$('div#error_' + sku).html('You must enter a valid quantity');
		return;
	}
	var total_qty = qty*pkg_qty;
	$.post('add_upsell_to_bag.html', {sku: sku, qty: total_qty },
		function(data) {
			if (data) {
				$('span#msg_' + sku).html('added!');
				$('a#cart_info b').html(data);
				cmCreatePageviewTag("ITEM ADDED TO CART", "2010", null);
				var price = parseFloat($('td#region_' + sku + ' p.price').html().replace('<b>Price:</b> $', '')) * qty;
				cmCreateShopAction5Tag(sku, $('td#region_' + sku + ' h4').html(), total_qty, price, $('input#cm_' + sku).val());
				cmDisplayShop5s();
			} else {
				$('div#error_' + sku).html('There was an error. Please try again.');
			}
		}
	);
	$('input#qty_' + sku).val('');
}

var personalize_save_for_later = function() {
	var args = '';
	$('form#customize input, form#customize textarea, form#customize select').each (function() {
	 	if($(this).val() != '') {
		    args += $(this).attr('name') + '=' + $(this).val().replace('&', '~||').replace('=', '~|||') + '&';
	    }
	});
	$.post($('input#save_for_later_url').val(), args, function(data) {
		hide('jquery-loginbox');
	    $('html,body').attr({scrollTop: 0});
	    if(data) {
		    if(!$('div#saved_message').length) {
			    $('div#notes').append($(document.createElement('div')).attr('id', 'saved_message').html('Success! To retrieve this, click on "my account" in the header and then select My Saved Projects.'));
		    }
	    } else {
		    $('div#notes').append($(document.createElement('div')).attr('id', 'saved_message').html('We were unable to save your project. Please try again.'));
	    }
	});
	return false;
};

