function AddToCompare() {
    /* Private variables */
    /* @var products: used to store all the attribute set and each key will be sored ; maximum 4 products */
    var attributeSets = {};
	/* Public variables */
	this.compareBoxTop=0;
	/* @function to fill the compare box on page load when the localStorge have the produts [last time added] */
	this.init=function(){
		var sessionStore=localStorage['attributeSet'+categoryID];
		if(sessionStore!='' && typeof sessionStore!='undefined' && sessionStore!='{}' ){
			var record=$.parseJSON(sessionStore);
			if(new Date().getTime() < record.timestamp){
				attributeSets=record['value'];
				this.markCheckedItems()
				this.render(categoryID); 
				$('.compare_count').html(this.getCompareProductCount(categoryID));
			}
			else{
				this.removeFromLocalStorage(categoryID);
			}
		}
	}
	
	/* @function to check and add class to product list LI */
	this.markCheckedItems=function(){	
		for (x in attributeSets[categoryID]) {
			   var id=attributeSets[categoryID][x]['id'];
			   $("[rel='checkbox_compare_" + id + "']").prop('checked','checked');
			   $("[rel='product_" + id + "']").addClass('compare-selected');
			}
	}
	
	/* @function to check the new product set id is matched with already existed one. If it is other ; user can't add that item into compare box */
	this.checkSetMatchTrue=function(setkey){
		for(key in attributeSets[categoryID]){
			if(attributeSets[categoryID][key]['setkey']!=setkey){
				return true
			}
		}
		return false;
	}
    
	/* @function to add new comparable product to attribute set */
    this.addNewComparableProduct = function (prodObj) {
        var id = prodObj['id'];
        var category = prodObj['category'];
        var setkey = prodObj['setkey'];
        var products = {};
		if(this.checkSetMatchTrue(setkey)){
			$("[rel='checkbox_compare_" + id + "']").removeAttr('checked');
			this.renderError('setDifferent',category);
			return false;
		}
		else{
			/* if the no. of products exceed the maximum limit of 4 */
			if(this.getCompareProductCount(categoryID) > 3){
				$("[rel='checkbox_compare_" + id + "']").removeAttr('checked');
				this.renderError('maxLimit',category);
				return false;
			}
			if (typeof attributeSets[categoryID] != 'undefined') {
				products[id] = prodObj;
				if(!this.checkProductExist(id)){
					/* merge the new object with already existed object usning custom $.objMerge function */
					attributeSets[categoryID] = $.objMerge(attributeSets[categoryID], products);
				}
			} else {
				products[0] = prodObj;
				attributeSets[categoryID] = products;
			}
			/* add a new class for the selected to compare product' s 'LI'  */
			this.markCheckedItems();
			this.saveToStorage();
			return true;
		}
    }
	
	/* @function to check the product existed in currecnt category */
	this.checkProductExist=function(id){
		for(key in attributeSets[categoryID]){
			if(attributeSets[categoryID][key]['id']==id){
				return true;
			}
		}
		return false;
	}
    
	/* @function to retrive all attribute sets */
    this.listAttributeSets = function () {
        return attributeSets;
    }
    
	/* @function to get a particular attribute set */
    this.getAttributeSet = function (attributeKey) {
        var attributeSetsArr = new Array();
        for (x in attributeSets[attributeKey]) {
            attributeSetsArr.push(attributeSets[attributeKey][x]);
        }
        return attributeSetsArr;
    }
    
	/* @function to get the count of entire attribute set count */
    this.getAttributeSetsCount = function () {
        return $.objCount(attributeSets);
    }
    
	/* @function to get the  product count of particular attribute set */
    this.getCompareProductCount = function (attributeKey) {
        return $.objCount(attributeSets[attributeKey]);
    }
    
	/* @function to remove one product */
    this.removeComparableProduct = function (prodObj) {
        var id = prodObj['id'];
        $("[rel='product_" + id + "']").removeClass('compare-selected');
        $("[rel='checkbox_compare_" + id + "']").removeAttr('checked');
        var key = this.getProductKey(categoryID, id);
        delete attributeSets[categoryID][key];
		if(!$.objCount(attributeSets[categoryID])>0){
			delete attributeSets[categoryID];
			this.removeFromLocalStorage(categoryID);
		}
		this.saveToStorage();
		return true;
    }
	
	/* @function to remove all items form a particular category. Also remove from the localStorage */
	this.removeAllItemsInCategory=function(){
		delete attributeSets[categoryID];
		this.removeFromLocalStorage(categoryID);
		this.render(categoryID);
	}
	
	/* @function to get the product key from Attributeset */
    this.getProductKey = function (attributeKey, productID) {
        for (x in attributeSets[attributeKey]) {
            if (attributeSets[attributeKey][x]['id'] == productID) {
                return x;
            }
        }
    }
	
	/* @function to draw the add to compare box with products or blank image */
    this.render = function (categoryID) {
		$(".addToCompareCommonDiv").removeClass('inactive');
        $(".addToCompareCommonDiv").addClass('active');
		var actData= addToCompare.getAttributeSet(categoryID);
        var data = {"products": addToCompare.getAttributeSet(categoryID)};
		/* Create html from template #addToCompareTemplate [productCompareBox.tpl] and the object which are selected */
        var html = $("#addToCompareTemplate").render(data, {'setkey': categoryID});
		if(!$.isEmptyObject(actData)){
			$("#addToCompare").html(html);
			if(this.getCompareProductCount(categoryID) > 1){
				$(".compareProduct").removeClass('disabled');
			}
			else{
				$(".compareProduct").addClass('disabled');
			}
		}
		else{
			this.clearAllCompareConatiner()
		}
    }
	
	/* @function to clear the div of compare box[When user closes the compare box, remove all items form block] */
	this.clearAllCompareConatiner=function(){
		$("#addToCompare").html('');
		$(".closecomperror").trigger('click');
		$(".compareIt").removeAttr('checked');
		$(".compare-selected").removeClass('compare-selected');
		$(".addToCompareCommonDiv").removeClass('active');
        $(".addToCompareCommonDiv").addClass('inactive');
	}
	
	/* @function to show the error messege on product's setID is different; new Porduct setID != already existed product's SetID */
	this.renderError=function(type,category){
		/* Create html error message from template #compareErrorTemplate[productCompareBox.tpl] and the object which are selected */
        var html = $("#compareErrorTemplate").render({"msgtype":type,"category":category});
        $(".compareError").html(html);
	}
	
	/* @function to save the object into browser localStorage */
	this.saveToStorage=function(){
		/* check the web broser have appropriate size available for storing the object string */
		if(Math.round($.getWebStorageRemainingSize('localStorage'))==0){
			this.removeOtherCategorylocalStorage();
		}
		var oneday =  24 * 60 * 60 * 1000;
		localStorage['attributeSet'+categoryID]= JSON.stringify({value: attributeSets, timestamp: new Date().getTime() + oneday})
		
	}
	
	/* @function to remove the local Data of particular category */
	this.removeFromLocalStorage=function(categoryID){
		localStorage.removeItem("attributeSet"+categoryID);
	}
	
	/* @function to remove the localStorage varibale other than currest category to create storage space */
	this.removeOtherCategorylocalStorage=function(){
		for(x in localStorage){
			/* check whether the key is current category */
			if(x!="attributeSet"+categoryID){
				this.removeFromLocalStorage(categoryID);
			}
		}
	}
	
}

/* create object of AddtoCompare */
var addToCompare = new AddToCompare();
addToCompare.init();

/* event driven codes */
$(document).ready(function () {
	
	//$( ".productTitle" ).draggable({ helper: "clone",cursor:"move" });
    $(document).on("change", ".compareIt", function () {
        var prodObj = 	$(this).data();
		var addCompare;
        if (this.checked) {
			/* add the obejct into Our private object "attributeSets" */
            addCompare = addToCompare.addNewComparableProduct(prodObj);
        } else {
			/* remove the obejct form Our private object "attributeSets" */
            addCompare=addToCompare.removeComparableProduct(prodObj)
        }
        if(addCompare){
			/* if the object is added successfully then render the html from Object */
			addToCompare.render(categoryID);
		}
		$('.compare_count').html(addToCompare.getCompareProductCount(categoryID));
    });
    
	$(document).on("click", ".closeit", function () {
        var prodObj = 	$(this).data();
		/* if the user clicks on close button ; them empty the obejct */
        var addCompare=addToCompare.removeComparableProduct(prodObj);
		if(addCompare){
			/* if the object is removed successfully then render the html from empty Object make div empty*/
			addToCompare.render(categoryID);
			$('.compare_count').html(addToCompare.getCompareProductCount(categoryID));
		}
    });
	
	$(document).on('click',".compareProduct",function(){
		var data 	= 	addToCompare.getAttributeSet(categoryID);
		var productIDs=[];
		/* when the user click on compare button ;get all the prduct ids from Object */
		for(key in data){
			productIDs.push(data[key]['id']);
		}
		/* only redirect the page if the object contains 2 or more productIDs */
		if(addToCompare.getCompareProductCount(categoryID) > 1){
			window.location=siteUrl+"/product/compare/products/"+productIDs.join("-")+"/";
		}
	});
	
	/* Close the error div */
	$(document).on("click",".closecomperror",function(){
		$("#compareError").html('');
	})
	
	/* if the user scroll down the page the compare box will add a class fixed for CSS positioning */
	$(window).scroll(function () {
		if($(".sorting-pane").length>0){
			if(!this.compareBoxTop>0){
				this.compareBoxTop= parseInt($(".sorting-pane").position().top) +212;
			}
		}
		else{
			if(!this.compareBoxTop>0){
				this.compareBoxTop= 192;
			}
			
		}
			if ( $(window).scrollTop() > this.compareBoxTop) {
				$(".addToCompareCommonDiv").addClass('fixed');
			}
			else{
				$(".addToCompareCommonDiv").removeClass('fixed');
			}
		
	});
	
	$(document).on('click',".clearAllItems",function(){
		addToCompare.removeAllItemsInCategory();
		addToCompare.clearAllCompareConatiner();
	});
	
	$(document).on('click',".closeBtnCompare",function(){
		addToCompare.removeAllItemsInCategory();
		addToCompare.clearAllCompareConatiner();
	});
});