/*!
 * Product Comparison v1.0
 * http://www.phpjabbers.com/product-comparison/
 * 
 * Copyright 2014, PHPJabbers
 * 
 */
(function (window, undefined){
	"use strict";
	pjQ.$.ajaxSetup({
		xhrFields: {
			withCredentials: true
		}
	});
	var document = window.document,
		routes = [
		          	{pattern: /^#!\/Load$/, eventName: "loadComparison"},
		          	{pattern: /^#!\/Load\/category_id:(\d+)?$/, eventName: "loadComparison"}
		         ];
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnProperty(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function hashBang(value) {
		if (value !== undefined && value.match(/^#!\//) !== null) {
			if (window.location.hash == value) {
				return false;
			}
			window.location.hash = value;
			return true;
		}
		
		return false;
	}
	
	function onHashChange() {
		var i, iCnt, m;
		for (i = 0, iCnt = routes.length; i < iCnt; i++) {
			m = window.location.hash.match(routes[i].pattern);
			if (m !== null) {
				pjQ.$(window).trigger(routes[i].eventName, m.slice(1));
				break;
			}
		}
		if (m === null) {
			pjQ.$(window).trigger("loadComparison");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function ProductCom(opts) {
		if (!(this instanceof ProductCom)) {
			return new ProductCom(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	ProductCom.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	ProductCom.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	ProductCom.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;
			this.category_id = null; 
			this.opts = {};
			
			return this;
		},
		
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("pcContainer_" + this.opts.index);
			this.$container = pjQ.$(this.container);
			
			this.$container.on("click.pc", ".pcSelectorLocale", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var locale = pjQ.$(this).data("id");
				self.opts.locale = locale;
				pjQ.$(this).addClass("pcLocaleFocus").parent().parent().find("a.pcSelectorLocale").not(this).removeClass("pcLocaleFocus");
				
				var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionLocale"].join("");
				if(self.opts.session_id != '')
				{
					ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionLocale", "&session_id=", self.opts.session_id].join("");
				}
				
				pjQ.$.get(ajax_url, {
					"locale_id": locale
				}).done(function (data) {
					if (!hashBang("#!/Load")) {
						pjQ.$(window).trigger("loadComparison");
					}
				}).fail(function () {
					log("Deferred is rejected");
				});
				return false;
			}).on("change.pc", "#pcCategory_" + self.opts.index, function (e) {
				hashBang("#!/Load/category_id:" + pjQ.$(this).val())
			});
			
			pjQ.$(window).on("loadComparison", this.$container, function (e, category_id) {
				self.category_id = category_id;
				self.loadComparison.call(self);
			});
			
			if (window.location.hash.length === 0) {
				this.loadComparison.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		loadComparison: function () {
			var self = this,
				index = this.opts.index,
				params = { "index": this.opts.index,
							"product_id": this.opts.product_id,
							"category_id": self.category_id
						 };
			if(self.opts.session_id != "")
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionIndex"].join(""), params).done(function (data) {
				self.$container.html(data);
				self.bindComparison.call(self);
			}).fail(function () {
				
			});
		},
		bindComparison: function () {
			var self = this;
			var	index = this.opts.index;
			
			pjQ.$(".pjPcs-table:not(.pjPcs-table-main) thead").on('click', function(){
				pjQ.$(this).toggleClass('active').next().toggle();
			});
			pjQ.$('.pjPcs-checkbox').each(function(){
				if (pjQ.$(this).find('input').attr('checked')) {
					pjQ.$(this).addClass('active');
				} else {
					pjQ.$(this).removeClass('active');
				};
			});
			pjQ.$('.pjPcs-checkbox').change(function(){
				pjQ.$(this).toggleClass('active');
				var model_id = pjQ.$(this).attr('data-id');
				var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSetModel"].join("");
				if(self.opts.session_id != '')
				{
					ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionSetModel", "&session_id=", self.opts.session_id].join("");
				}
				pjQ.$.ajax({
					type: "GET",
					cache: false,
					dataType: "json",
					data: {"model_id": model_id, "product_id": self.opts.product_id},
					url: ajax_url,
					xhrFields: {
					      withCredentials: true
					},
					success: function (data) {
						self.loadComparison.call(self);
					}
				});
			});
		}
	};
	
	window.ProductCom = ProductCom;	
})(window);