/**
 * E-Junkie cart tweaks 
 * 
 * Copyright 2011 Brightflock
 * 
 * XXX-CL - this does another load to initially set cart to US--probably more optimal to reload once pay button is clicked.
 */

(function($) {
	var ZIP_LABEL = 'Postal Code';
	var DECLARE_TEXT = 'Check here if you are Canadian, as tax will apply. We’ll need your postal code to calculate what tax applies in your region.';
	var DEFAULT_COUNTRY = 'US';
	var DEFAULT_ZIP = '90210';
	var TAX_COUNTRY = 'CA';
	var POLL_TIME = 300;
	var POLL_TIMEOUT = 60000;
	
	$("<style type='text/css'>" +
			"#EJEJC_window form { display: none; overflow: hidden !important; }" +
			"#EJEJC_iframeContent { overflow: auto !important; height: 420px !important; }" +
			"table#ejejctable { width: auto !important; }" +
	  "</style>").appendTo("head");
	
	$(document).ready(function() {
		$('a[target="ej_ejc"]').click(function() {
			var $ej = $('body > #EJEJC_window');
			var wait = 0;
			var firstTime = true;
			
			var f = function() {
				var $form = $('#EJEJC_iframeContent form:first', $ej)
				
				if ($form.length) {
					
					var $table = $('table#ejejctable', $form);
					
					var $updateCartButton = $('input#btnUpdtCart', $table).click(function() {
						$form.hide();
						wait = 0;
						setTimeout(f, POLL_TIME)
					});
					
					var $country = $('select[name="to_country"]', $ej);
					var $zip = $('input[name="zipcode"]', $ej);
					var $countrytr = $country.parents('tr:first');
					var $ziptr = $zip.parents('tr:first');
					
					$('div', $ziptr.children('td:first')).html(ZIP_LABEL);
					
					$countrytr.parent().prepend('<tr><td colspan=5><input type="checkbox" name="declare" style="width: 40px;"/> ' +	DECLARE_TEXT + '</td></tr>');
					
					var $declare = $('input[name="declare"]', $countrytr.parent());
					
					var declareUpdate = function() {
						if ($declare.filter(':checked').length == 1) {
							$country.val(TAX_COUNTRY);
							
							if ($zip.val() == DEFAULT_ZIP) {
								$zip.val('');
							}
						}
						else {
							$country.val(DEFAULT_COUNTRY);
							$zip.val(DEFAULT_ZIP);
						}
					};
							
					$declare.change(function() {
						declareUpdate();
						$updateCartButton.click();
					});
					
					$countrytr.hide();
					
					if ($country.val() == TAX_COUNTRY) {
						$declare.attr('checked', 'checked');
						$ziptr.show();
					}
					else {
						$declare.removeAttr('checked');
						$ziptr.hide();
					}

					declareUpdate();
					
					if ($updateCartButton.length && firstTime) {
						firstTime = false;
						
						$declare.trigger('change');
					}
					else {
						
						$form.show();
					}
				}
				else {
					if (wait < POLL_TIMEOUT) {
						wait += POLL_TIME;
						setTimeout(f, POLL_TIME);
					}
					else {
						$form.show()
					}
				}
			};
			
			setTimeout(function() {
				f($ej);
			}, POLL_TIME);
		});
	});
})(jQuery);
