function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function cemTransactionItem() {
	
	this.code = null;
	this.name = "";
	this.category = "";
	this.unitPrice = 0;
	this.quantity = 1;
	
	this.getCode = function() {
		return this.code;
	}
	
	this.setCode = function(code) {
		this.code = code;
	}
	
	this.getName = function() {
		return this.name;
	}
	
	this.setName = function(name) {
		this.name = name;
	}
	
	this.getCategory = function() {
		return this.category;
	}
	
	this.setCategory = function(category) {
		this.category = category;
	}
	
	this.getUnitPrice = function() {
		return this.unitPrice;
	}
	
	this.setUnitPrice = function(unitPrice) {
		this.unitPrice = unitPrice;
	}
	
	this.getQuantity = function() {
		return this.quantity;
	}
	
	this.setQuantity = function(quantity) {
		this.quantity = quantity;
	}
}

function cemTransaction() {
	
	this.orderId = null;
	this.storeName = null;
	this.total = 0;
	this.tax = 0;
	this.shipping = 0;
	this.city = null;
	this.state = null;
	this.country = null;
	this.items = new Array();
	
	this.getOrderId = function() {
		return this.orderId;
	}
	
	this.setOrderId = function(orderId) {
		this.orderId = orderId;
	}
	
	this.getStoreName = function() {
		return this.storeName;
	}
	
	this.setStoreName = function(storeName) {
		this.storeName = storeName;
	}
	
	this.getTotal = function() {
		return this.total;
	}
	
	this.setTotal = function(total) {
		this.total = total;
	}
	
	this.getTax = function() {
		return this.tax;
	}
	
	this.setTax = function(tax) {
		this.tax = tax;
	}
	
	this.getShipping = function() {
		return this.shipping;
	}
	
	this.setShipping = function(shipping) {
		this.shipping = shipping;
	}
	
	this.getCity = function() {
		return this.city;
	}
	
	this.setCity = function(city) {
		this.city = city;
	}
	
	this.getState = function() {
		return this.state;
	}
	
	this.setState = function(state) {
		this.state = state;
	}
	
	this.getCountry = function() {
		return this.country;
	}
	
	this.setCountry = function(country) {
		this.country = country;
	}
	
	this.getItems = function() {
		return this.items;
	}
	
	this.setItems = function(items) {
		this.items = items;
	}
}

function cemAnalytics () {

    this.query = null;
    this.attributes = new Object();
		this.nb_attributes = 0;
		this.nb_attribute_values = 0;
		this.tags = new Array();
		this.isRelax = false;		
		this.miss_chunks = new Array();
		this.relax = new Object();
		this.relax_nb_choices = 0;
		this.action = new Object();
		this.relax_suggestion = null;
		this.rec_type = null;
		this.prodId = null;
		this.quantity = null;
		this.transaction = new cemTransaction();
		this.context_string = "";
		this.tagsLabels = new Object();
		this.error = null;
		this.errorLabel = null;
		
		this.setError = function(label, e) {
			this.error = e;
			this.errorLabel = lable;
		}
		
		this.hasError = function() {
			return this.error != null;
		}
		
		this.getErrorLabel = function() {
			return this.errorLabel;
		}
		
		this.getError = function() {
			return this.error;
		}
		
		this.setTagsLabels = function(tagsLabels) {
			this.tagsLabels = tagsLabels;
		}
		
		this.getTagsLabels = function() {
			return this.tagsLabels;
		}
	
		this.setQuery = function(query) {

        this.query = query;
    };
    
    this.getQuery = function() {
        return this.query;
    };
    
    this.setIsRelax = function(isRelax) {
    	this.isRelax = isRelax;
    	if(isRelax) {
	    	this.increaseRelaxationDisplayCount();
	    }
	  }
    
    this.getIsRelax = function() {
    	//"relax_nb_choices" in _cem_analytics
    	return this.isRelax;
    }
    
    this.preferences_size = 0;
    this.preferences = new Object();
    this.setProfileAttributeValueWeight = function(attribute, value, weight) {
    	if(!(attribute in this.preferences)) {
    		this.preferences[attribute] = new Object();
    	}
    	if(!(value in this.preferences[attribute])) {
    		this.preferences_size++;
    	}
    	this.preferences[attribute][value] = weight;
    }
    
    this.getProfiledInterestsAsString = function() {
    	return JSON.stringify(this.preferences);
    }
    
    this.getProfiledInterestsAsValue = function() {
    	return this.preferences_size;
    }
    
    this.getTopPreferenceName = function(index) {
    	var maxes = new Array();
    	maxes[0] = -1;
    	maxes[1] = -1;
    	maxes[2] = -1;
    	var maxAttributes = new Array();
    	maxAttributes[0] = null;
    	maxAttributes[1] = null;
    	maxAttributes[2] = null;
    	
    	for(var attribute in this.preferences) {
    		var m = -1;
    		var obj = this.preferences[attribute];
    		for(var value in obj) {
    			if(m == -1 || m < this.preferences[attribute][value]) {
	    			m = this.preferences[attribute][value];
	    		}
    		}
    		if(maxes[0] == -1 || maxes[0] < m) {
    			maxes[2] = maxes[1];
    			maxes[1] = maxes[0];
    			maxAttributes[2] = maxAttributes[1];
    			maxAttributes[1] = maxAttributes[0];
    			maxes[0] = m;
    			maxAttributes[0] = attribute;
    		}
    		else if(maxes[1] == -1 || maxes[1] < m) {
    			maxes[2] = maxes[1];
    			maxAttributes[2] = maxAttributes[1];
    			maxes[1] = m;
    			maxAttributes[1] = attribute;
    		}
    		else if(maxes[2] == -1 || maxes[2] < m) {
    			maxes[2] = m;
    			maxAttributes[2] = attribute;
    		}
    	}
    	
    	if(index < 3 && index >= 0) {
    		return maxAttributes[index];
    	}
    	return null;
    }
    
    this.getPreferenceValue = function(name) {
    	var maxVal = "_UNDEFINED";
    	if(typeof(this.preferences[name]) != "undefined") {
    		var obj = this.preferences[name];
    		var max = -1;
    		for(var value in obj) {
    			if(max == -1 || obj[value] > max) {
    				max = obj[value];
    				maxVal = value;
    			}
    		}
    	}
    	return maxVal;
    }
    
    this.addAttributeValues = function(attribute, values) {
			if(typeof(values)=='string') {
				var vals = new Array();
				vals[0] = values;
				values = vals;
			}
			this.attributes[attribute] = values;
			this.nb_attributes++;
			this.nb_attribute_values += values.length;
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
		}
		
		this.getAttributes = function() {
			return this.attributes;
		}
		
		this.getNbAttributeValues = function() {
			return this.nb_attribute_values;
		}
		
		this.addTag = function(tag) {
			this.tags.push(tag);
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
		}
		
		this.getTags = function() {
			return this.tags;
		}
		
		this.setMissChunksFromTermFilters = function(termFilters) {
			var tmp = "";
			var diff = 0;
			if(termFilters != "" && this.query != "") {
				var words = this.query.trim().split(' ');
				var wordsb = termFilters.trim().split(' ');
				for(var i=0; i<words.length; i++) {
					if(words[i] == wordsb[i-diff]) {
						tmp += words[i]+' ';
					} else {
						diff++;
						if(i-diff >= 0 && words[i] == wordsb[i-diff]) {
							tmp += words[i]+' ';
						}
						else if(tmp != "") {
							this.miss_chunks.push(tmp.trim());
							tmp = "";
						}
					}
				}
				if(tmp != "") {
					this.miss_chunks.push(tmp.trim());
				}
			}
			if(!this.isRelax && this.query != "" && this.miss_chunks.length == 0 && this.nb_attributes == 0 && this.tags.length == 0) {
				this.miss_chunks.push(this.query);
			}
		}
		
		this.getMissChunks = function() {
			if(typeof(this.miss_chunks)=='string') {
				var vals = new Array();
				vals[0] = this.miss_chunks;
				return vals;
			}
			return this.miss_chunks;
		}
		
		this.setRelaxNbChoices = function(relax_nb_choices) {
			this.relax_nb_choices = relax_nb_choices;
		}
		
		this.addRelaxAttributeValues = function(attribute, values) {
			//alert(JSON.stringify(relax[i].filters[k]));
			this.relax[attribute] = values[0];
		}
		
		this.addRelaxTag = function(tag) {			
			this.tags = new Object();
			this.relax[tag] = "true";
		}
		
		this.getRelaxAsString = function() {
			return JSON.stringify(this.relax);
		}
		
		this.getRelaxNbChoices = function() {
			return this.relax_nb_choices;
		}
		
		this.setSearchAction = function(newSearch) {
			if(newSearch) {
				this.action.type = "search_new";
			} else {
				this.action.type = "search_refine";
			}
			this.increaseGuidanceInteractionCounts(newSearch);
			this.increaseSearchCount();
		}
		
		this.isSearchAction = function() {
			return this.action.type == "search_new" || this.action.type == "search_refine";
		}
		
		this.clearWhenNotSearch = function() {
			this.query = null;
	    this.attributes = new Object();
			this.nb_attributes = 0;
			this.nb_attribute_values = 0;
			this.tags = new Array();
			this.isRelax = false;		
			this.miss_chunks = new Array();
			this.relax = new Object();
			//this.relax_nb_choices = 0;
		}
		
		this.setSortAction = function() {
			this.clearWhenNotSearch();
			this.action.type = "sort";
			this.increaseGuidanceInteractionCounts(true);
		}
		
		this.resetGuidanceInteractionCounts = function() {
			createCookie('cem_interact_count', 0, 1);
		}
		
		this.increaseGuidanceInteractionCounts = function(resetCounter) {
			if(resetCounter) {
				this.resetGuidanceInteractionCounts();
			}
			
			var interactions = this.getInteractionCount();
			createCookie('cem_interact_count', interactions+1, 1);
			var total_interactions = this.getTotalInteractionCount();
			createCookie('cem_interact_total_count', total_interactions+1, 100);
		}
		
		this.increaseSearchCount = function() {
			var interactions = this.getSearchCount();
			createCookie('cem_search_count', interactions+1, 100);
		}
		
		this.getSearchCount = function() {
			var interactions = readCookie('cem_search_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.increaseRecsCount = function() {
			var interactions = this.getRecommendationClickCount();
			createCookie('cem_recs_count', interactions+1, 100);
		}
		
		this.getRecommendationClickCount = function() {
			var interactions = readCookie('cem_recs_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.increaseRelaxationDisplayCount = function() {
			var interactions = this.getRelaxationDisplayCount();
			createCookie('cem_relax_display_count', interactions+1, 100);
		}
		
		this.getRelaxationDisplayCount = function() {
			var interactions = readCookie('cem_relax_display_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.increaseRelaxationSolvedCount = function() {
			var interactions = this.getRelaxationSolvedCount();
			createCookie('cem_relax_solved_count', interactions+1, 100);
		}
		
		this.getRelaxationSolvedCount = function() {
			var interactions = readCookie('cem_relax_solved_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.increaseGuidanceCount = function() {
			var interactions = this.getGuidanceCount();
			createCookie('cem_guidance_count', interactions+1, 100);
		}
		
		this.getGuidanceCount = function() {
			var interactions = readCookie('cem_guidance_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.increaseFilterChangeCount = function() {
			var interactions = this.getFilterChangeCount();
			createCookie('cem_filterchange_count', interactions+1, 100);
		}
		
		this.getFilterChangeCount = function() {
			var interactions = readCookie('cem_filterchange_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.getInteractionCount = function() {
			var interactions = readCookie('cem_interact_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.getTotalInteractionCount = function() {
			var interactions = readCookie('cem_interact_total_count');
			if(interactions == null) {
				interactions = 0;
			}
			return parseInt(interactions);
		}
		
		this.setFilterAttributeAddAction = function(attribute, value) {
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
			this.clearWhenNotSearch();
			this.action.type = "filter_attribute_add";
			this.attributes[attribute] = new Array();
			this.attributes[attribute].push(value);
			this.increaseGuidanceInteractionCounts(true);
			this.increaseGuidanceCount();
		}
		
		this.setFilterAttributeRemoveAction = function(attribute, value) {
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
			this.clearWhenNotSearch();
			this.action.type = "filter_attribute_remove";
			this.attributes[attribute] = new Array();
			this.attributes[attribute].push(value);
			this.increaseGuidanceInteractionCounts(true);
			this.increaseFilterChangeCount();
		}
		
		this.setFilterGuidanceAddAction = function(attribute, value, resetCounter) {
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
			this.clearWhenNotSearch();
			this.action.type = "guidance_attribute_add";
			this.attributes[attribute] = new Array();
			this.attributes[attribute].push(value);
			this.increaseGuidanceInteractionCounts(resetCounter);
			this.increaseGuidanceCount();
		}
		
		this.isGuidanceAction = function() {
			return this.action.type == "filter_attribute_add" || this.action.type == "guidance_attribute_add" || this.action.type == "filter_tag_add";
		}
		
		this.isChangeFilterAction = function() {
			return this.action.type == "filter_attribute_remove" || this.action.type == "filter_tag_remove";
		}
		
		this.setFilterTagAddAction = function(tag, resetCounter) {
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
			this.clearWhenNotSearch();
			this.action.type = "filter_tag_add";
			this.tags = new Array();
			this.tags.push(tag);
			this.increaseGuidanceInteractionCounts(resetCounter);
			this.increaseGuidanceCount();
		}
		
		this.getContextAsString = function() {
			return this.context_string;
		}
		
		this.setFilterTagRemoveAction = function(tag) {
			this.context_string = JSON.stringify(this.attributes) + JSON.stringify(this.tags);
			this.clearWhenNotSearch();
			this.action.type = "filter_tag_remove";
			this.tags = new Array();
			this.tags.push(tag);
			this.increaseGuidanceInteractionCounts(true);
			this.increaseFilterChangeCount();
		}
		
		this.setFilterRelaxationSolvedAction = function(suggestion) {
			this.clearWhenNotSearch();
			this.action.type = "relaxation_solved";
			this.relax_suggestion = suggestion_param;
			this.increaseGuidanceInteractionCounts(true);
			this.increaseRelaxationSolvedCount();
		}
		
		this.setProductRecommendationClickAction = function(rec_type, prodId) {
			this.clearWhenNotSearch();
			this.action.type = "recommendation_click";
			this.rec_type = rec_type;
			this.prodId = prodId;
			this.increaseGuidanceInteractionCounts(true);
			this.increaseRecsCount();
		}
		
		this.engagementAction = "";
		
		this.setProductEngagementAction = function(engagementAction, prodId, quantity) {
			this.clearWhenNotSearch();
			this.action.type = "product_engagement_action";
			this.engagementAction = engagementAction;
			this.prodId = prodId;
			this.quantity = quantity;
		}
		
		this.getEngagementAction = function() {
			return this.engagementAction;
		}
		
		this.getProdId = function() {
			return this.prodId;
		}
		
		this.getQuantity = function() {
			return parseInt(this.quantity);
		}
		
		this.isProductEngagementAction = function() {
			return this.action.type == "product_engagement_action";
		}
		
		this.setStartCheckoutAction = function() {
			this.clearWhenNotSearch();
			this.action.type = "start_checkout";
		}
		
		this.isStartCheckoutAction = function() {
			return this.action.type == "start_checkout";
		}
		
		this.setFailTransactionAction = function() {
			this.clearWhenNotSearch();
			this.action.type = "fail_transaction";
		}
		
		this.isFailTransactionAction = function() {
			return this.action.type == "fail_transaction";
		}
		
		this.isRecommendationAction = function() {
			return this.action.type == "recommendation_click";
		}
		
		this.getRecType = function () {
			return this.rec_type;
		}
		
		this.getFilterRelaxationSolvedSuggestion = function() {
			return this.relax_suggestion;
		}
		
		this.getAction = function() {
			if(! ("type" in this.action)) {
				return null;
			}
			return this.action.type;
		}
		
		this.getTransaction = function() {
			return this.transaction;
		}
		
		this.setTransaction = function(transaction) {
			this.clearWhenNotSearch();
			this.action.type = "transaction";
			this.transaction = transaction;
		}
		
		this.isTransactionAction = function() {
			return this.action.type == "transaction";
		}
}


