// FOXYCART.JS
// v0.7.1


if ( ! window.jQuery) {
	alert('This page does not have jQuery loaded. Please add jQuery to your website to ensure FoxyCart functions properly. If you are a customer seeing this alert please notify the owner of this website about it.')
}
var FC = FC || {};
FC.json = {};
FC.session_id = '';
FC.session_name = 'fcsid';
var cookiepath = cookiepath || '';


// CONSTRUCTOR
FC.client = function(storedomain, sitedomain, cookiepath) {
	// Initialize some variables
	this.storedomain = storedomain;
	this.sitedomain = sitedomain.replace(/https?:\/\//i, '').replace(/www\./i, '').replace(/\/.*$/, '');
	this.cookiepath = cookiepath || '';
}


// SESSIONS
FC.client.prototype.session_initialized = false;
FC.client.prototype.session_get = function() {
	if (FC.session_id != "") {
		this.session_initialized = true;
		return "&"+FC.session_name+"="+FC.session_id;
	}
	this.regex = new RegExp('#'+FC.session_name+'=([A-Za-z0-9]*)');
	if (this.regex.test(window.location.href)) { // check for the session in
													// the URL, overwrite any
													// existing session
		var fc_match = this.regex.exec(window.location.href);
		FC.session_id = fc_match[1];
		this.session_set(FC.session_name, FC.session_id); // Reset the cookie
	} else if (document.cookie.indexOf(FC.session_name + "=") > -1) { // retrieve
																		// the
																		// session
																		// from
																		// the
																		// cookie
		var c_start=document.cookie.indexOf(FC.session_name + "=");
		if (c_start != -1) {
			c_start = c_start + FC.session_name.length + 1;
			var c_end = document.cookie.indexOf(";",c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			FC.session_id = unescape(document.cookie.substring(c_start,c_end));
		}
	} else if (FC.json.length > 0) { // retrieve the session from the JSON,
										// set a cookie
		// set a cookie for next time
		FC.session_id = FC.json.session_id;
		this.session_set(FC.session_name, FC.session_id);
	}
	if (FC.session_id != "") {
		this.session_initialized = true;
		return "&"+FC.session_name+"="+FC.session_id;
	} else {
		return "";
	}
};
FC.client.prototype.session_set = function() {
	// Determine what level to set the cookie on based on the store domain
	var sitedomain = this.sitedomain.split('.');
	if (sitedomain[0] == 'www') sitedomain.shift();

	var currentdomain = window.location.href.split('/');
	currentdomain = currentdomain[2].split('.');
	var i = currentdomain.length - sitedomain.length;
	while (i>0) {
		currentdomain.shift();
		i--;
	}
	currentdomain = "." + currentdomain.join('.');
	if (currentdomain == ".foxycart.com") return false;
	document.cookie = FC.session_name + "=" + escape(FC.session_id) + ";path=/" + this.cookiepath + ";domain="+currentdomain;
	return true;
}
FC.client.prototype.session_apply = function() {
	var self = this;

	// Links, first set events for existing links, then for dynamically created
	// links
	// TODO: address the triplication here
	jQuery('a:not([href*=' + FC.session_name + '=])[href*=' + this.storedomain + ']').each(function(){
		jQuery(this).attr('href', jQuery(this).attr('href') + self.session_get()).click(function(){
			return self.cart_submit(this, self.cart_prepare_element(this));
		});
	}).live('click', function(event){
		jQuery(this).attr('href', jQuery(this).attr('href') + self.session_get()).click(function(){
			// Necessary to actually add the binding for subsequent clicks
			return self.cart_submit(this, self.cart_prepare_element(this));
		});
		// Necessary to process it on the first click
		return self.cart_submit(this, self.cart_prepare_element(this));
	});

	// Forms
	// TODO: address the duplication? works well without the .submit() _except_
	// for random forms...
	jQuery('form:not(:has(input[name='+FC.session_name+']))[action*=' + this.storedomain + ']').prepend('<input type="hidden" name="'+FC.session_name+'" value="'+FC.session_id+'">').live('hover focus', function(){
		if (jQuery(this).children('input[name=fcsid]').length == 0) {
			jQuery(this).prepend('<input type="hidden" name="'+FC.session_name+'" value="'+FC.session_id+'">');
		}
	}).submit(function(){
		return self.cart_submit(this, self.cart_prepare_element(this));
	});
	jQuery('form[action*=' + this.storedomain + ']').live('submit', function(){
		return self.cart_submit(this, self.cart_prepare_element(this));
	});
}



// CART UPDATING, JSON
FC.client.prototype.cart_update = function() {
	var self = this;
	jQuery.getJSON('https://' + this.storedomain + '/cart.php?cart=get&output=json' + this.session_get() + '&callback=?', function(data) {
		// alert('JSON is ready');
		FC.json = data;
		if ( ! self.session_initialized == true) {
			self.session_initialized = true;
			FC.session_id = data.session_id;
			self.session_set();
			self.session_get();
		}
		self.session_apply();

		// "Minicart" Helpers
		(FC.json.product_count > 0) ? jQuery("#fc_minicart, .fc_minicart").show() : jQuery("#fc_minicart, .fc_minicart").css("display","none");
		// update values
		jQuery("#fc_quantity, .fc_quantity").html("" + FC.json.product_count);
		jQuery("#fc_total_price, .fc_total_price").html("" + self._currency_format(FC.json.total_price));
	});
};
FC.client.prototype.cart_submit = function(e, arr) {
	if (this.events.cart.preprocess.execute(e, arr) == false) return false;
	if (this.events.cart.process.funcs.length == 0) {
		return true;
	} else{
		return this.events.cart.process.execute(e, arr);
	}
}
FC.client.prototype.cart_prepare_element = function(e) {
	var qs = '';
	if (e.tagName == 'A') {
		qs = e.href.match(/\?(.*)$/);
		qs = qs[1];
	} else if (e.tagName == 'FORM') {
		qs = jQuery(e).serialize();
	}
	qs.replace(/\|\|[A-Za-z0-9]{64}(\|\|open)?/g, '');
	return this._unserialize(qs);
}



// EVENT (a class to create executable arrays of functions)
FC.client.event = function() {
	this.funcs = new Array;
}
FC.client.event.prototype.add = function(f) {
	if( typeof f != "function" ) {
		f = new Function(f);
	}
	this.funcs.push(f);
}
FC.client.event.prototype.add_pre = function(f) {
	if( typeof f != "function" ) {
		f = new Function(f);
	}
	this.funcs.unshift(f);
}
FC.client.event.prototype.execute = function(e, arr) {
	var success = true;
	for( var i=0; i<this.funcs.length; i++ ) {
		if ( this.funcs[i](e, arr) == false ) {
			i = this.funcs.length;
			success = false;
		}
	}
	return success;
}


// EVENTS (the object to hold the executable arrays)
FC.client.prototype.events = {
	cart: []
}


// HELPERS
FC.client.prototype._unserialize = function(Data){ // jQuery Unserialize v1.0
													// by James Campbell
	var Data = Data.split("&");
	var Serialized = new Array();
	jQuery.each(Data, function(){
		var Properties = this.split("=");
		Serialized[Properties[0]] = Properties[1];
	});
	return Serialized;
};
FC.client.prototype._currency_format = function(amount) {
	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;
	return s;
}




// INIT
FC.client.prototype.init = function() {
	this.cart_update();
}
