getProductsInCart = function() {
	var product = jQuery(".foxee_products:first").clone(true);
	jQuery("div#foxee_products_container").empty();
	
	if(typeof fc_json != 'undefined' && fc_json.products.length > 0) {
		jQuery.each(fc_json.products, function() {
			fe_prod = this;
			jQuery.each(fe_json.field_map, function(fe_key) {
				val = '';
				if( typeof fe_prod[this] != 'undefined' )
					val = fe_prod[this];
				if( fe_key.match(/price/) )
					val = formatPrice(val);
				if( fe_key.match(/percent/) )
					val = formatPercent(val);
				if( fe_key.match(/weight/))
					val = formatFloat(val, null);
				
				if( fe_key =='foxee_remove_link' ) {
					val = jQuery(product).find('a.fe_RemoveProduct');
					jQuery(val).attr('id', fe_prod.id);
				}
				
				jQuery(product).find("."+fe_key).text(val);
			});
			
			jQuery("div#foxee_products_container").append(product);
			product	= jQuery(product).clone(true);
		});
		
		jQuery("div#foxee_products_container").show();
	} else {
		jQuery("div#foxee_products_container").append(product);
		jQuery("div#foxee_products_container").hide();
	}
}

formatFloat = function(amount, type) {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = "";
	if(i < 0) { minus = "-"; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf(".") < 0) { s += ".00"; }
	if(s.indexOf(".") == (s.length - 2)) { s += "0"; }
	s = minus + s;
	if( type == 'price' ) {
		if( fe_json.currency_before == '1' )
			s = fe_json.currency_symbol+s;
		else
			s = s+fe_json.currency_symbol;
	} else if( type == 'percent' ) {
		s = s+'%';
	} else {
		s = parseFloat(s);
	}
	
	return s;
}

formatPercent = function(val) {
	return formatFloat(val, 'percent');
}

formatPrice = function(val) {
	return formatFloat(val, 'price');
}

fe_UpdateCoupons = function() {
	if( typeof fc_json == 'undefined' || typeof fc_json.coupons != 'object') return;
	var coupon = jQuery('div.foxee_coupons:first').clone(true);
	jQuery("div#foxee_coupons_container").empty();
	
	if( fc_json.coupons.length > 0 ) {
		jQuery.each(fc_json.coupons, function(cp) {
			jQuery(coupon).find(".foxee_coupon").text(cp);
		});
		jQuery("div#foxee_coupons_container").append(coupon);
		coupon = jQuery(coupon).clone(true);
	} else {
		jQuery("div#foxee_coupons_container").append(coupon);
		jQuery("div#foxee_coupons_container").hide();
	}
}

fe_UpdateCart = function() {
	if( typeof fe_json == 'undefined' ) return;
	getProductsInCart();
	jQuery.each(fe_json.field_map, function(fe_key) {
		val = '';
		if( typeof fc_json != 'undefined' && typeof fc_json[this] != 'undefined' )
			val = fc_json[this];
		if( fe_key == 'foxee_coupons' )
			fe_UpdateCoupons();
		if( typeof val == 'object' ) return;
		if( fe_key.match(/price/) )
			val = formatPrice(val);
		if( fe_key.match(/percent/) )
			val = formatPercent(val);
		if( fe_key.match(/weight/))
			val = formatFloat(val, null);
		jQuery("div#foxee_cart_container #"+fe_key).text(val);
	});
	
	var hide_cart = jQuery('div#foxee_cart_container').attr('rel');
	if( hide_cart && hide_cart.match(/hide_cart\=true/) && fc_json.products.length == 0 )
		jQuery("div#foxee_cart_container").hide();
	else
		jQuery("div#foxee_cart_container").show();
	
	jQuery('a.foxycart').unbind('click');
	fc_tb_init('a.foxycart');
	jQuery('a.fe_RemoveProduct').unbind('click');
	jQuery('a.fe_RemoveProduct').bind('click', fe_RemoveProduct);
}

fe_UpdateRelated = function() {
	if(typeof fe_related_updates == "undefined") return false;
	jQuery.each(fe_related_updates, function() {
		var params = {ACT: fe_AjaxACT, func: 'foxee_relate_updates', fcsid: fc_json.session_id};
		jQuery.extend(params, this);
		if( typeof params.replace == "undefined" ) return;
		var $replace = jQuery('.'+params.replace);
		delete params.replace;
		if( $replace.length == 0 ) return;
		jQuery.ajax({
			url: fe_url,
			data: params,
			dataType: 'html',
			type: 'GET',
			success: function(data) {
				$replace.empty();
				$replace.append(data);
			}
		});
	});
}

fe_RemoveProduct = function() {
	var id = jQuery(this).attr('id');
	var url = "https://" + FoxyDomain + "/cart.php?cart=update&output=json&callback=fc_FoxyJSON&id="+id+"&quantity=0"+fc_AddSession();
	jQuery.getScript(url);
	return false;
}

//this is called from fc_PreProcess.
fe_DonationProduct = function(data, id) {
	var ret = true;
	jQuery.each(data, function(key) {
		if( !key.match(/donation_amount$/) ) return;
		var amount = formatFloat(this, null);
		var number = key.match(/^x\:([0-9]+)/);
		if(number == null)
			number = '';
		else
			number = number[1]+':';
		var max = formatFloat(data['x:'+number+'donation_max'], null);
		var min = formatFloat(data['x:'+number+'donation_min'], null);
		if( max != 0 && amount > max ) {
			alert("Donation Amount must be less then "+formatPrice(max));
			ret = false;
		}
		
		if( min != 0 && amount < min ) {
			alert("Donation Amount must be more then "+formatPrice(min));
			ret = false;
		}
		
		data[number+'price'] = amount;
	});
	
	return ret;
}

parseParams = function(url) {
	var params=url;
	if (url.match(/\?(.+)$/))
		params = RegExp.$1;
	//decode the url
	params = jQuery.URLDecode(params);
	// split the params
	var pArray = params.split("&");
	// hash to store result
	var pHash = {};
	// parse each param in the array and put it in the hash
	for(var i=0;i<pArray.length;i++) {
		var temp = pArray[i].split("=");
		pHash[temp[0].replace(/^h\:/, '')] = unescape(temp[1]);
	}
	return pHash;
}

serializeObj = function(obj) {
	var str = "";
	jQuery.each(obj, function(i,n) {
		str += i+'='+n+'&';
	});
	return str.replace(/\&$/, '');
}

fc_PreProcess = function(data, id) {
	data = parseParams(data); //lets make an object from the string
	
	if( fe_DonationProduct(data, id) == false )
		return false;
	
	if(typeof data.PHPSESSID != "undefined") {
		delete data.PHPSESSID;
	}
	jQuery.extend(data, {
		fc_session_id: fc_json.session_id,
		func: 'order_form_cache',
		ACT: fe_AjaxACT
	});
	
	jQuery.ajax({
		url: fe_url,
		type: 'POST',
		data: data,
		dataType: 'jsonp',
		success: fe_BuildCart
	});
	
	return false;
}

fc_BuildFoxyCart = function() {
	jQuery.each(fe_update, function(index, value) {
		if(typeof value == "function")
			value();
	});
}

fe_FoxeeJSON = function(json) {
	fe_json = json;
	fe_UpdateCart();
}

fe_ResizeCheckoutIframe = function(height) {
	jQuery('iframe.foxycart').css('height', height + 'px');
}

fe_BuildCart = function(json) {
	if( typeof json.callback != 'undefined' ) delete json.callback;
	var block_fb = false;
	if( typeof json.block_fb != 'undefined' ) {
		if( json.block_fb == 'true' )
			block_fb = true;
		delete json.block_fb;
	}
	
	var MyFoxyData = serializeObj(json);
	// if we want to go directly to the checkout or do a redirect, don't show the foxybox 
	if(MyFoxyData.match("cart=checkout")) {
		if(typeof fe_checkout_iframe != "undefined" && fe_checkout_iframe != '') {
			var $insert = jQuery('.'+fe_checkout_iframe);
			if( $insert.length > 0 ) {
				$insert.empty().append('<iframe src="https://'+FoxyDomain+'/cart.php?'+MyFoxyData+fc_AddSession()+'" class="foxycart" />');
			}
			return false;
		}
		
		location.href = "https://" + FoxyDomain + "/cart.php?" + MyFoxyData + fc_AddSession();
	} else if(MyFoxyData.match("cart=updateinfo") || MyFoxyData.match("redirect=")) {
		location.href = "https://" + FoxyDomain + "/cart.php?" + MyFoxyData + fc_AddSession();
	} else {
		var url = "https://" + FoxyDomain + "/cart.php?" + MyFoxyData + fc_AddSession();
		if( block_fb != false ) {
			jQuery.getScript(url+'&output=json&callback=fc_FoxyJSON');
		} else {
			// show ThickBox
			fc_tb_show(null,"https://" + FoxyDomain + "/cart.php?" + MyFoxyData + fc_AddSession(),false);
			// Add to Thick Box's close link so that it will update the cart
			jQuery("a.fc_tb_closeWindowButton").click(function(){
				fc_UpdateCart(FoxyDomain);
				return false;
			});
		}
	}
	return false;
}

fe_NumbersOnly = function(str) {
	if( typeof str == 'string' ) {
		str = str.replace(/[^0-9]/, '');
	} else if( typeof str == 'object' ) {
		str = jQuery(str).val();
		str = str.replace(/[^0-9]/, '');
	} else {
		str = '';
	}
	return str;
}

jQuery(document).ready(function() {
	jQuery.ajax({
		url: fe_url,
		data: {ACT: fe_AjaxACT, func: 'foxee_json'},
		dataType: 'jsonp',
		success: fe_FoxeeJSON
	});
	
	jQuery('a.foxycart_link').bind('click', function() {
		var id = jQuery(this).attr('id').match(/[0-9]+$/);
		if(id == null) return false;
		jQuery('form#foxycart_'+id[0]).trigger('submit');
		return false;
	});
	jQuery('input[name="cc_number"]').bind('keyup', function() {
		jQuery(this).val(fe_NumbersOnly(this));
	});
	jQuery('input[name="cc_number"]').bind('change', function() {
		jQuery(this).val(fe_NumbersOnly(this));
	});
	jQuery('a.fe_updateinfo, a.fe_checkout').unbind('click');
	jQuery('a.fe_updateinfo, a.fe_checkout').bind('click', function() {
		fc_PreProcess(jQuery(this).attr('href'), this);
		return false;
	});
	jQuery('form#fe_profile_form').bind('submit', function() {
		jQuery('.fe_profile_message').hide();
		jQuery('.fe_profile_error').hide();
		
		if(jQuery(this).find('input[name="ACT"]').val() != fe_AjaxACT)
			return true;
		
		jQuery.ajax({
			url: fe_url,
			data: jQuery(this).serialize(),
			dataType: 'json',
			success: function(data) {
				if( data.success == '1' ) {
					jQuery('.fe_profile_message').empty();
					jQuery('.fe_profile_message').append(data.message);
					jQuery('.fe_profile_message').show();
					
					if( data.return_url != '' && data.no_redirect != '1' ) {
						setTimeout(function() {
							window.location = data.return_url;
						}, parseInt(data.timer));
					}
				} else {
					jQuery('.fe_profile_error').empty();
					message	= 'The following errors occured'+"\n"+'<ul>'+"\n";
					jQuery.each(data.errors, function() {
						message += '<li>'+this.toString()+'</li>'+"\n";
					});
					message	+= '</ul>'+"\n";
					jQuery('.fe_profile_error').append(message);
					jQuery('.fe_profile_error').show();
				}
			}
		});
		
		return false;
	});
	
	jQuery.extend({
		URLEncode: function(c){
			var o='';
			var x=0;
			c=c.toString();
			var r=/(^[a-zA-Z0-9_.]*)/;
			while(x<c.length) {
				var m=r.exec(c.substr(x));
				if(m!=null && m.length>1 && m[1]!='') {
					o+=m[1];x+=m[1].length;
				} else {
					if(c[x]==' ') {
						o+='+';
					} else {
						var d=c.charCodeAt(x);
						var h=d.toString(16);
						o+='%'+(h.length<2?'0':'')+h.toUpperCase();
					}
					x++;
				}
			}
			return o;
		},
		URLDecode: function(s) {
			var o=s;
			var binVal,t;
			var r=/(%[^%]{2})/;
			while((m=r.exec(o))!=null && m.length>1 && m[1]!='') {
				b=parseInt(m[1].substr(1),16);
				t=String.fromCharCode(b);o=o.replace(m[1],t);
			}
			return o;
		}
	});
});

var fe_json;
var fe_AjaxACT = '36';
var fe_url = 'http://www.review.net/';
fe_url = fe_url.replace(/^(https?\:\/{2})[^\/]+/i, "$1"+location.host);
var fe_update = [fe_UpdateCart, fe_UpdateRelated];
var fe_related_updates = [];
