jQuery(document).ready(function() {
	//Inject word breaks into barefooters page
	
	function wbr(str, num) { 
	  return str.replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,char){
		 return text + "<wbr/>" + char;
	  });
	}
	
	
	jQuery('.barefooter_info h4 a, .barefooter_info dd').each(function(){
		
		jQuery(this).html(wbr(jQuery(this).text(), 6));
		
		
	});
	
	if(jQuery('.beachrescue a[rel*=popup]').length > 0){
		jQuery('.beachrescue a[rel*=popup]').facebox();
		jQuery('.beachrescue a[rel*=popup]').live(function() {
			jQuery(this).bgiframe();
		});
	}
	if(jQuery('.beachrescue #poll_form a[rel*=popup]').length > 0){
		jQuery('.beachrescue #poll_form a[rel*=popup]').facebox();
		jQuery('.beachrescue #poll_form a[rel*=popup]').live(function() {
			jQuery(this).bgiframe();
		});
	}
});
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/** 
 * JSON Cookie - jquery.jsoncookie.js
 *
 * Sets and retreives native JavaScript objects as cookies.
 * Depends on the object serialization framework provided by JSON2.
 *
 * Dependencies: jQuery, jQuery Cookie, JSON2
 * 
 * @project JSON Cookie
 * @author Randall Morey
 * @version 0.9
 */
(function ($) {
	var isObject = function (x) {
		return (typeof x === 'object') && !(x instanceof Array) && (x !== null);
	};
	
	$.extend({
		getJSONCookie: function (cookieName) {
			var cookieData = $.cookie(cookieName);
			return cookieData ? JSON.parse(cookieData) : {};
		},
		setJSONCookie: function (cookieName, data, options) {
			var cookieData = '';
			
			options = $.extend({
				expires: 90,
				path: '/'
			}, options);
			
			if (!isObject(data) && data.constructor != Array) {	// data must be a true object to be serialized
				throw new Error('JSONCookie data must be an object');
			}
			
			cookieData = JSON.stringify(data);
			
			return $.cookie(cookieName, cookieData, options);
		},
		removeJSONCookie: function (cookieName) {
			return $.cookie(cookieName, null);
		},
		JSONCookie: function (cookieName, data, options) {
			if (data) {
				$.setJSONCookie(cookieName, data, options);
			}
			return $.getJSONCookie(cookieName);
		}
	});
})(jQuery);
/*
    http://www.JSON.org/json2.js
    2008-05-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects without a toJSON
                        method. It can be a function or an array.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the object holding the key.

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array, then it will be used to
            select the members to be serialized. It filters the results such
            that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
    charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
    getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
    parse, propertyIsEnumerable, prototype, push, replace, slice, stringify,
    test, toJSON, toString
*/

if (!this.JSON) {

// Create a JSON object only if one does not already exist. We create the
// object in a closure to avoid creating global variables.

    JSON = function () {

        function f(n) {
            // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            gap,
            indent,
            meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            },
            rep;


        function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

            escapeable.lastIndex = 0;
            return escapeable.test(string) ?
                '"' + string.replace(escapeable, function (a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    return '\\u' + ('0000' +
                            (+(a.charCodeAt(0))).toString(16)).slice(-4);
                }) + '"' :
                '"' + string + '"';
        }


        function str(key, holder) {

// Produce a string from holder[key].

            var i,          // The loop counter.
                k,          // The member key.
                v,          // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }

// What happens next depends on the value's type.

            switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

                return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

            case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

                if (!value) {
                    return 'null';
                }

// Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

// If the object has a dontEnum length property, we'll treat it as an array.

                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                    mind + ']' :
                              '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

// If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value, rep);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value, rep);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
            }
        }

// Return the JSON object containing the stringify and parse methods.

        return {
            stringify: function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

                var i;
                gap = '';
                indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }

// If the space parameter is a string, it will be used as the indent string.

                } else if (typeof space === 'string') {
                    indent = space;
                }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                         typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

                return str('', {'': value});
            },


            parse: function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

                var j;

                function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' + ('0000' +
                                (+(a.charCodeAt(0))).toString(16)).slice(-4);
                    });
                }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

                if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                    j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                    return typeof reviver === 'function' ?
                        walk({'': j}, '') : j;
                }

// If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('JSON.parse');
            }
        };
    }();
}

/**
 * @author mgharibi
 */
/*
 * xml feeds
 * http://devstore.barefootwine.com/ewinerysolutionsproductfeed
 * http://devstore.barefootwine.com/ewinerysolutionsproductfeed?format=json
 * http://devstore.barefootwine.com/ewinerysolutionsproductfeed?fields=productname&orderby=productname&type=thirdpartywine&productname=Barefoot%20Bubbly%20Chardonnay%20Brut%20Cuvee
 * http://devstore.barefootwine.com/ewinerysolutionsproductfeed?fields=productname,appellation&orderby=productname&type=thirdpartywine&appellation=California
 * http://devstore.barefootwine.com/ewinerySolutionsProductFeed?fields=all&orderby=price1&type=thirdpartywine&price1Low=10&price1High=50
 * 
 * cookies
 * cartProducts
 * shippingState
 * memberStatus
 * cartSubTotal
 * 
 * cartProducts Cookie
 * qty: an integer specifying the number of a product purchased
 * productID: the productID of the product. Should be obtained from the product feed. 
 * isCase: a Boolean value specifying whether the product is being sold in a case or not
 * productpriceID: this value will be blank for wine products, and will have a value for non-wine products. Each non-wine product SKU will have a unique productpriceid. This should be obtained from the product feed.\
 * type: specifies the product type. This should be obtained from the product feed.
 *
 * example: &quantity1=10&productID1=9d5dc4bf-1cc4-fbb6-2355-956f2f72b4ff&isCase1=0&productpriceid1=&type1=firstpartywine&quantity2=2&productID2=9d5dc4bf-1cc4-fcc6-2455-956f2f72b4ff&isCase2=1&productpriceid2=&type2=firstpartywine
 * json:    [{"quantity":"10","productID":"9d5dc4bf-1cc4-fbb6-2355-956f2f72b4ff","isCase":"0","productpriceid":"","type":"firstpartywine"},{"quantity":"2","productID":"9d5dc4bf-1cc4-fbb6-2355-9ff89fkjhkjfkj","isCase":"1","productpriceid":"","type":"firstpartywine"}}
 */

//http://barefootwine.ewinerysolutions.com/ewinerysolutionsproductfeed?fields=all&format=json&productsku=0862311OS
	 	//http://dev.barefootwine.com/productData.htm		
		//$.getJSON("http://devstore.barefootwine.com/ewinerySolutionsProductFeed?fields=all&format=json",
		
 var GLOBAL_DOMAIN_NAME;
 // when DOM is loaded, check for product code and load store integration parts
 $(document).ready(function () {
 	var stateSelected = $.getUrlVar('state');
	var cartShipTo = $.cookie("SHIPPINGSTATE");
	if(stateSelected=="false" && cartShipTo == null){
		openShipTo(null,null);
	}
	 var productSku = $("#productSku").html();	 
/*	 if(productSku != null){	 	
	    //http://devstore.barefootwine.com/ewinerysolutionsproductfeed?fields=all	 	
		$.getJSON("http://barefootwine.ewinerysolutions.com/ewinerysolutionsproductfeed?fields=all&format=json&format=json&callback=?&productsku=" + productSku,
			function(data){
				if(data.products.length > 0){
				    document.productData = data.products[0];				
				    loadPriceInformation();
				    enableBuyButtons();				
				    //updateCartInformation();	
				}
			}
		
		);
	 }else{
*/	 

	    // get all products
	    $.getJSON("http://devstore.barefootwine.com/ewinerysolutionsproductfeed?fields=all&format=json&callback=?",
			function(data){
				
				//alert("JSON Data: " + data.length);				
				document.allProducts = data.products;				
				if(productSku!=null){
				    document.productData = new Object();
				    for(var x =0; x< data.products.length; x++){
					    if(data.products[x].SHIPPINGSKU.toString().replace(".0","") == productSku){
						    document.productData = data.products[x];		
						    break;				
					    }
				    }				    
				}
				
				loadPriceInformation();
				enableBuyButtons();				
				
				/*
				var addToCartHTML = "<input id='productQty' style='float:left;' value='1' type='textbox' size=1></input>";
				addToCartHTML += "<div style='margin-left:5px;float:left;cursor:pointer;cursor:hand;background-color:purple;width:82px;height:22px;color:white;'><div style='padding-top: 3px; padding-left: 9px;' onclick='addBottlesToCart(false)'>Add to cart</div></div>";
				addToCartHTML += "<div style='margin-left:5px;float:left;cursor:pointer;cursor:hand;background-color:purple;width:110px;height:22px;color:white;'><div style='padding-top: 3px; padding-left: 9px;' onclick='addBottlesToCart(true)'>Add case to cart</div></div>";
				addToCartHTML += "<div style='margin-left:5px;float:left;cursor:pointer;cursor:hand;background-color:purple;width:130px;height:22px;color:white;'><div style='padding-top: 3px; padding-left: 9px;' onclick='location.href=\"http://www.thebarrelroom.com/index.cfm?method=storecart.showcart\"'>View Cart/Checkout</div></div>";				
				$(addToCartHTML).appendTo("#storeControls");
				*/
								
				
				// set domain for cookie (needed for subdomains)
				var domainArray = window.location.hostname.split(".");
				if(domainArray.length == 3){
				    GLOBAL_DOMAIN_NAME = domainArray[1] + "." + domainArray[2];
				}else if(domainArray.length == 2){
				    GLOBAL_DOMAIN_NAME = domainArray[0] + "." + domainArray[1];
				}
				
				updateCartInformation();
				
			}
		
		);
	 //}
	 
 });

function loadPriceInformation(){
    $(".price").each(function(index){
        //alert(index + ': ' + $(this).text());    
        var sku = $(this).attr("sku");
        var product = getProductBySku(sku);
        if(product != null){
            $(this).html(formatCurrency(product.PRICE1) + " / Bottle<br />" + formatCurrency(product.PRICE2) +" / Case")
        }
    });
    
    
}

function getProductBySku(sku){
    for(var x =0; x< document.allProducts.length; x++){
	    if(document.allProducts[x].SHIPPINGSKU.toString().replace(".0","") == sku){
		    return document.allProducts[x];				
	    }
    }
    return null;
}

function enableBuyButtons(){
    $('.addBottle').click(function() {
      var productSku = $(this).attr("sku");
      addBottlesToCart(false,productSku);
    });
    
    $('.addCase').click(function() {
      var productSku = $(this).attr("sku");
      addBottlesToCart(true,productSku);
    });
}

function getTotalsInCart(){
	var cartProducts = $.JSONCookie("CARTPRODUCTS");	
	var cartTotal = new Object();
	var totalQty = 0;
	var subTotal = 0.0;
	if (cartProducts.length != undefined) {
		for (var p = 0; p < cartProducts.length; p++) {
			var pObj = cartProducts[p];					
			totalQty += parseInt(pObj.QUANTITY);
			
			// determine cost for this item and add to total
			for(var i = 0; i < document.allProducts.length; i++){
				if(pObj.PRODUCTID == document.allProducts[i].PRODUCTID){
					if(pObj.ISCASE == "1"){
					    subTotal += parseFloat(document.allProducts[i].PRICE2) * (parseInt(pObj.QUANTITY));
					}else{
					    subTotal += parseFloat(document.allProducts[i].PRICE1) * (parseInt(pObj.QUANTITY));
					}
					break;
				}
			}
			
		}
	}
	cartTotal.totalQty = totalQty;
	cartTotal.subTotal = subTotal;
	return cartTotal;
}

function setShippingState(stateCode){    
    $.cookie("SHIPPINGSTATE", stateCode, {path: '/', domain:GLOBAL_DOMAIN_NAME});
    closeShipTo();
}

function addBottlesToCart(isCase, pSku){
		// get cartProducts cookie
	var cartProducts = $.JSONCookie("CARTPRODUCTS");	
	var cartShipTo = $.cookie("SHIPPINGSTATE");
	
	if(cartShipTo == null){
	        openShipTo(isCase,pSku);
	        return false;
	}
	
	//$('#cartInfo').html('').html(JSON.stringify(cartProducts));
		
	var productData;
	
	if(document.allProducts==null){
	    productData = document.productData;
	}else{
		for(var x =0; x< document.allProducts.length; x++){
			if(document.allProducts[x].SHIPPINGSKU.toString().replace(".0","") == pSku){
				productData = document.allProducts[x];		
				break;				
			}
		}
	}
	
	
	if (productData != null) {
	
		var recordExists = false;
		if (cartProducts.length != undefined) {		    
			for (var p = 0; p < cartProducts.length; p++) {
				var pObj = cartProducts[p];
				if (pObj.PRODUCTID == productData.PRODUCTID) {
					if (pObj.ISCASE == isCase) {
						// updated current record
						pObj.QUANTITY = parseInt(pObj.QUANTITY) + 1; //((isCase == false) ? parseInt($("#productQty").val()) : 1)
						recordExists = true;
						break;
					}
				}
			}
		}else{
		    //openShipTo();
		}
	
		if (!recordExists) {
			var newProductObj = new Object();
			newProductObj.QUANTITY = 1; //(isCase == false) ? $("#productQty").val() :
			newProductObj.PRODUCTID = productData.PRODUCTID;
			newProductObj.ISCASE = (isCase) ? 1 : 0;
			newProductObj.PRODUCTPRICEID = "";
			newProductObj.TYPE = productData.TYPE;
			if (cartProducts.length != undefined) {
				cartProducts.push(newProductObj);
			}
			else {
				cartProducts = [newProductObj];
			}
		}
		
		$.JSONCookie("CARTPRODUCTS", cartProducts, {path: '/', domain:GLOBAL_DOMAIN_NAME});
		openAddToCart();
		
	}
	updateCartInformation();
}

function removeItem(arrayIndex){
	var cartProducts = $.JSONCookie("CARTPRODUCTS");
	if (cartProducts.length != undefined) {
		cartProducts.remove(arrayIndex);
		$.JSONCookie("CARTPRODUCTS", cartProducts, {path: '/', domain:GLOBAL_DOMAIN_NAME});
		updateCartInformation();
		
	}
}

function getProductByID(pID){
	for(var i = 0; i < document.allProducts.length; i++){
		if(pID == document.allProducts[i].PRODUCTID){
			return document.allProducts[i]
		}
	}
	return null;
}

function showCartContents(){
	$("#cartContents").slideDown("fast");
}

function hideCartContents(){
	$("#cartContents").slideUp("fast");
}

function updateCartInformation(){	
	var cartProducts = $.JSONCookie("CARTPRODUCTS");
	var cartTotal = getTotalsInCart();
	if (cartProducts.length != undefined) {
        $('#subTotal').html('').html("<b>" + formatCurrency(cartTotal.subTotal) + "</b>");
    }
    /*
	var totalItemsInCart = cartTotal.totalQty;	
	$('#cartInfo').html('').html("<p style='font-size:10px;'><br/>You currently have <a style='text-decoration:underline;' onclick='showCartContents();'>" + totalItemsInCart + " " + ((totalItemsInCart==1)?"item":"items") + "</a> in your shopping cart." + "<br/>Subtotal: " + formatCurrency(cartTotal.subTotal) + "</p>");
	if (cartProducts.length != undefined) {
		var htmlString = "<div id=\"closebtn\" style=\"cursor:hand;cursor:pointer;position:absolute;right:0px;top:0px;background-color:gray;color:white;border: 1px solid grey;\" onclick='hideCartContents();'>close</div><div style='height:15px;'></div>";		
		for (var p = 0; p < cartProducts.length; p++) {
			var pObj = cartProducts[p];					
			var productObj = getProductByID(pObj.productID);
			if(productObj != null){
				var conj = "";
				var price;
				if(pObj.isCase){
					conj = (parseInt(pObj.quantity) == 1) ? "case of" : "cases of" ;								
					price = productObj.PRICE2;
				}else{
					conj = (parseInt(pObj.quantity) == 1) ? "bottle of" : "bottles of" ;
					price = productObj.PRICE1;
				}				
				
				htmlString += "<div><li>%qty% %conjunction% %name%, %cost% - %delete%".replace("%qty%",pObj.quantity).replace("%name%",productObj.PRODUCTNAME).replace("%cost%",formatCurrency(parseFloat(price) * (parseInt(pObj.quantity)))).replace("%conjunction%",conj).replace("%delete%","<a onclick='removeItem(" + p + ")'>remove</a></li></div>");
			}
		}
		htmlString += "<hr style='width:100%'><div style='float:left'>Total Items: %totalQty%</div>".replace("%totalQty%",cartTotal.totalQty);
		htmlString += "<div style='float:right'>Subtotal: %totalCost%</div>".replace("%totalCost%",formatCurrency(cartTotal.subTotal));
		htmlString += "";
		$("#cartContents").html(htmlString);
	}
	*/
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

