var ProductViewer = function(options) {
	this.instanceName = false;
	this.is_alive = true;
	this.type = 'basic';
	this.list_type = 'playlist';
	this.limit = null;
	this.list = null;
	
	jQ.extend(true, this, options);
	/*
	var error = 'Product Viewer missing required parameters:\n';
	if (!this.instanceName) error += 'container\n';
	if (error != 'Product Viewer missing required parameters:\n') {
		alert(error);
		return;
	}
	*/
	
	this.container = jQ('#'+this.instanceName+'_container');

	if (!this.list && this.list_type == 'playlist') {
		this.no_list_error();
		return;
	}
	
	this.get_markup(); 
}

ProductViewer.prototype.get_markup = function() {
	
	var action;
	if (this.list_type == 'playlist') {
		action = 'get_object_list';
	} else if (this.list_type == 'new') {
		action = 'get_object_new';
	} else if (this.list_type == 'random') {
		action = 'get_object_random';
	} else if (this.list_type == 'category') {
		action = 'get_object_category';
	} else if (this.list_type == 'category_list') {
		action = 'get_multi_cat_object';
	}
	
	var PV = this;
	
	ONAPI.request({
		data: { module: 'products', action: action, user_id: userId, list: this.list, id: this.cat_id, limit: this.limit, type: this.type, cartCurrency: cartCurrency, 'return': true },
		callback: function(data) {
			if (typeof(PV.container.get(0)) != 'undefined') {
				PV.container.html(data);
				if (action == 'get_multi_cat_object') {
					PV.get_cat_list();
					PV.container.get(0).productViewer = PV;
					return;
				}
				PV.get_products_from_markup();
				PV.container.get(0).productViewer = PV;
				
				if (!jQ('#topBar').length) {
					function checkHash(hash) {
						cb.console('checkHash '+hash);
						if (hash.match('details_')) {
							cb.console('got hash '+hash.split('_')[1]);
							var id = hash.split('_')[1];
							if (typeof PV.products[id] != 'undefined') {
								cb.console('light box the below product');
								cb.console(PV.products[id]);
								PV.open_light_box(id);
							}
						} else if (hash.match('show-product-') && !productPermaLinkHandled) {
							var id = hash.split('product-')[1];
							if (typeof PV.products[id] != 'undefined') {
								cb.console('light box the below product for perma link');
								cb.console(PV.products[id]);
								PV.open_light_box(id);
								productPermaLinkHandled = true;
							}
						} else {
							jQ.fn.colorbox.close();
						}
					}
				
					historyCallbacks.push(checkHash);
					jQ.history.init(historyInit);
				}
			}
		},
		error: function(data) {
			PV.container.html('<h1>Error Loading Products</h1>');
		}
	});
}

ProductViewer.prototype.open_light_box = function(id) {
	if (jQ('#colorbox').find('#details_'+id+'_'+this.instanceName).length) { return; }
	
	var light_id ='#'+this.products[id].html.find('.light_box_identifier').attr('id');
	
	var settings = {
		inline:true,
		rel: this.instanceName,
		href: light_id,
		width:'700px',
		maxHeight: '90%',
		minHeight: '600px',
		current: '{current} of {total}',
		cbox_open: function() {
			jQ('#colorbox').css({'background-color':'#fff','border':'solid 1px #999'});
		},
		onComplete: function() {
			window.location.hash = 'details_'+id;
		},
		open: true
	};
	
	try {
		jQ.fn.colorbox(settings);
	} catch(e) {
	
	}
}

ProductViewer.prototype.get_products_from_markup = function() {
	this.products = {};
	var PV = this;
	this.container.find('.productList').each(function() {
		var product = {};
		product.is_bundle = false;
		if (jQ(this).hasClass('bundle_bundle')) product.is_bundle = true;
		var idsplit = this.id.split('_');
		var id = idsplit[1];
		var cat_id = idsplit[2];
		//if (jQ('#product_'+id+'_'+cat_id+'_sku').length) product.sku = jQ('#product_'+id+'_'+cat_id+'_sku').val();
		product.id = id;
		product.cat_id = cat_id;
		product.title = jQ(this).children('.productTitle').text();
		product.description = jQ(this).children('.productDesc').text();
		product.price = jQ(this).children('.productTitlePrice').text();
		product.status = jQ(this).find('.buy_button').attr('status');
		if (product.status == '') product.status = 0;
		product.img = jQ(this)
			.children('.productImg')
			.css('background-image')
			.replace('"', '')
			.replace('url(','')
			.replace(')','')
			.split('?')[0];
		jQ(this).children('.productImg').click(function() {
			window.location.hash = 'details_'+id;
		});
		product.html = jQ(this);
		
		PV.products[id] = product;
		
		if (product.is_bundle) {
			PV.get_bundled_products(product);
		}
		
		//give unique ids in case the product is shown elsewhere on the page
		this.id = this.id+'_'+PV.instanceName;
		var lbi = product.html.find('.light_box_identifier').get(0);
		lbi.id = lbi.id+'_'+PV.instanceName;
		var buybutt = product.html.find('a.buy_button').get(0);
		buybutt.id = buybutt.id+'_'+PV.instanceName;
		buybutt.rel = PV.instanceName;
		//buybutt.href = buybutt.href+'_'+PV.instanceName;
		
		if (!jQ('#topBar').length) PV.light_box(PV.products[id]);//jQ.history.load('#details_'+id);
	});
}

ProductViewer.prototype.get_bundled_products = function(p) {
	var PV = this;
	var r = {};
	//get bundled products
	p.html.find('.bundled_product').each(function() {
		var id = this.id.split('_')[2];
		r[id] = {};
		r[id].title = jQ(this).find('.prod_title_input').val();
		r[id].quantity = jQ(this).find('.prod_quantity_input').val();
		r[id].price = jQ(this).find('.prod_price_input').val();
		r[id].sku = jQ(this).find('.prod_sku_input').val();
		r[id].html = jQ(this);
	});
	
	p.required_products = r;
	var o = tb.getObjectFromDom('optionalProducts_'+p.id);
	
	//get optional products
	p.html.find('.optional_product_list').each(function(i) {
		jQ(this).find('.optional_product').each(function(j) {
			var id = this.id.split('_')[3];
			o[i]['Product'][id].title = jQ(this).find('.prod_title_input').val();
			o[i]['Product'][id].price = parseFloat(jQ(this).find('.prod_price_input').val());
			o[i]['Product'][id].sku = jQ(this).find('.prod_sku_input').val();
			o[i]['Product'][id].html = jQ(this);
			var checkbox = jQ(this).find('.optional_product_checkbox').get(0);
			o[i]['Product'][id].checkbox = checkbox;
			var ci = i;
			jQ(checkbox).click(function() {
				if (this.checked && jQ(this).attr('type') != 'radio') {
					var checks = 0;
					cb.console(ci);
					var op = PV.products[p.id].optional_products[ci]['Product'];
					var num_to_choose = PV.products[p.id].optional_products[ci].number_to_choose;
					for (var i in op) {
						if (typeof(op[i].checkbox) != 'undefined') {
							if (op[i].checkbox.checked) checks++; 
						}
					}

					if (checks > num_to_choose && num_to_choose != 0 && typeof num_to_choose != 'undefined') {
						alert('You have already selected the amount of Optional Products you must choose. De-select one before choosing another.');
						this.checked = false;
						return false;
					} else {
						jQ(this).parent().addClass('bundle_title_selected');
					}
				} else if (jQ(this).attr('type') == 'radio') {
					jQ(this).parents('.optional_product_list').find('.bundle_title_selected').removeClass('bundle_title_selected');
					jQ(this).parents('.bundle_title').addClass('bundle_title_selected');
				} else {
					jQ(this).parents('.bundle_title').removeClass('bundle_title_selected');
				}
			});
		});
	});
	
	cb.console('Got optional product from markup');
	cb.console(o);
	
	p.optional_products = o;
	p.number_to_choose = parseInt(jQ('#numbertochoose_'+p.id).val());
	
	jQ.extend(true, PV.products[p.id], p);
}

ProductViewer.prototype.light_box = function(p) {
	if (jQ('#colorbox').find('#details_'+id+'_'+this.instanceName).length) { cb.console('Already showing this product'); return; }
	
	var link = p.html.find('a.buy_button');
	link.attr('rel', this.instanceName);
	var id ='#'+p.html.find('.light_box_identifier').attr('id');
	var prod_id = p.id;
	//if (typeof(p.sku) != 'undefined') prod_id = p.sku;
	
	var buy_button_text = (parseInt(p.status)) ? 'add to cart' : 'out of stock';
	
	if (p.is_bundle) {
		jQ(id).find('.prodLightImg').prepend('<img src="'+p.img+'?h=300&w=300" style="cursor:pointer;" onclick="document.getElementById(\''+this.instanceName+'_container\').productViewer.open_full_size_image(this.src);"><p>Click image to enlarge.</p>');
		if(parseInt(p.status)) {
			jQ(id).find('.bundle_buy_container').children('div').append('<a class="bundle_buy_button" href="#" rel="'+p.status+'" onclick="document.getElementById(\''+this.instanceName+'_container\').productViewer.add_bundle_to_cart('+prod_id+','+p.status+');">'+buy_button_text+'</a>');
		} else {
			jQ(id).find('.bundle_buy_container').children('div').append('<a class="bundle_buy_button" href="#" rel="'+p.status+'" onclick="return false;">'+buy_button_text+'</a>');
		}
	} else {
		jQ(id).find('.prodLightImg').prepend('<img src="'+p.img+'?h=300&w=300" style="cursor:pointer;" onclick="document.getElementById(\''+this.instanceName+'_container\').productViewer.open_full_size_image(this.src);"><p>Click image to enlarge.</p>');
		if(parseInt(p.status)) {
			jQ(id).find('.prodLightImg > img').siblings('.prodLightQuantity').before('<a href="#" rel="'+p.status+'" onclick="document.getElementById(\''+this.instanceName+'_container\').productViewer.add_to_cart('+prod_id+','+p.status+');">'+buy_button_text+'</a>');
		} else {
			jQ(id).find('.prodLightImg > img').siblings('.prodLightQuantity').before('<a href="#" rel="'+p.status+'" onclick="return false;">'+buy_button_text+'</a>');
		}	
	}
	
	var sb = p.html.find('.scrollbox');
	var sbl = sb.children('.scrollboxleft');
	var sbr = sb.children('.scrollboxright');
	var sbi = sb.find('.photoblock');
	
	if (sbi.length > 1) {
		sbl.add(sbr).show();
	}
	
	sbl.click(function() {
		var showing = sbi.filter('.photoblockshowing');
		showing.animate({width:0},500,function(){
			jQ(this).removeClass('photoblockshowing');
		});
		if (showing.prev().length) {
			showing.prev().animate({width:240},500,function(){
				jQ(this).addClass('photoblockshowing');
			});
		} else {
			sbi.eq(sbi.length-1).animate({width:240},500,function(){
				jQ(this).addClass('photoblockshowing');
			});
		}
	});
	
	sbr.click(function() {
		var showing = sbi.filter('.photoblockshowing');
		showing.animate({width:0},500,function(){
			jQ(this).removeClass('photoblockshowing');
		});
		if (showing.next().length) {
			showing.next().animate({width:240},500,function(){
				jQ(this).addClass('photoblockshowing');
			});
		} else {
			sbi.eq(0).animate({width:240},500,function(){
				jQ(this).addClass('photoblockshowing');
			});
		}
	});
	
	sb.find('.photoCategoryImageThumb').unbind().bind('click', function() {
		var src = jQ(this).css('background-image').replace('url(','').replace(')','').replace('"','').split('?')[0]+'?h=300&w=300';
		jQ('#colorbox').find('.prodLightImg img').attr('src', src);
	});
	
	try {
	
		p.html.colorbox({
			inline:true,
			rel: this.instanceName,
			href: id,
			width:'700px',
			maxHeight: '90%',
			minHeight: '600px',
			current: '{current} of {total}',
			cbox_open: function() {
				jQ('#colorbox').css({'background-color':'#fff','border':'solid 1px #999'});
			},
			onComplete: function() {
				jQ.history.load('details_'+p.id);
			}
		});
	} catch(e) {
		cb.console('Caught error in colorbox '+e);
	}
}

ProductViewer.prototype.add_to_cart = function(id, status) {
	var PV = this;
	if(!status || typeof(status) == 'undefined')
	{
		jQ('#colorbox').prepend('<div id="productStatus_error" style="margin:5px;text-align:center;font-weight:bold;">This Item Is Not Available At This Time. Please Check Again Later.</div>');
		var fadeout = function(){
			jQ('#colorbox > #productStatus_error').fadeOut(1000, function(){
				jQ(this).remove();
			});
		}
		setTimeout(fadeout, 3000);
		return;
	}
	var p = {};
	p[id] = {};
	p[id]['quantity'] = jQ('.prodLightQuantity').find('input').val();
	
	p[id]['options'] = {};
	if (jQ('#colorbox').find('.prodLightOptions:visible').length) {
		jQ('#colorbox').find('.prodLightOptions:visible').find('select').each(function() {
			p[id]['options'][this.id.split('_')[1]] = this.value;
		});
	}
	
	p[id]['subscription'] = {};
	if (jQ('#colorbox').find('.prodLightSub:visible').length) {
		jQ('#colorbox').find('.prodLightSub:visible').find('select').each(function() {
			p[id]['subscription'][this.id.split('_')[1]] = this.value;
		});
	}
	
	try {
		add_to_cart(p, function(response) {
			
		});
	} catch(err) {
		alert('cannot add items to cart in editor');
	}
	window.location.hash = '#';
	//dumbass colorbox
	if(status) jQ('#cboxClose').click();
}

ProductViewer.prototype.add_bundle_to_cart = function(id, status) {
	if(!status || typeof(status) == 'undefined')
	{
		jQ('#colorbox').prepend('<div id="productStatus_error" style="margin:5px;text-align:center;font-weight:bold;">This Item Is Not Available At This Time. Please Check Again Later.</div>');
		var fadeout = function(){
			jQ('#colorbox > #productStatus_error').fadeOut(1000, function(){
				jQ(this).remove();
			});
		}
		setTimeout(fadeout, 3000);
		return;
	}
	
	var PV = this;
	
	var product = PV.products[id];
	var p = {};
	p[id] = {}; //bundle id
	p[id]['quantity'] = jQ('.prodLightQuantity').find('input').val(); //bundle quantity
	
	//get required products
	/*var r = {};
	for (var i in product.required_products) {
		var rp = product.required_products[i];
		r.push({});
		var last = r.length-1;
		r[last].id = i;
		r[last].options = [];
		rp.html.find('.bundled_product_option_'+i).each(function() { //get options if any
			r[i].options.push(this.value);
		});
	}*/
	p[id].required_products = tb.getObjectFromDom('bundled_product_list_'+id); //store required products
	if(typeof(p[id].required_products) == 'undefined') {
		p[id].required_products = {};	
	}
	
	//get optional products
	var o = [];
	
	if (product.optional_products) {
		cb.console(product.optional_products);
		//eval('product.optional_products = '+product.optional_products);
		if (product.optional_products.constructor == Array || product.optional_products.constructor == Object) {
			cb.console(product.optional_products);
			for (j = 0; j < product.optional_products.length; j++) {
				var checked = 0;
				var group = product.optional_products[j];
				var title = group.title;
				cb.console('Group '+title);
				for (var i in group.Product) {
					var op = group.Product[i];
					cb.console(op);
					if (jQ('#optional_product_'+j+'_'+i).find('.optional_product_checkbox:checked').length) { //if product is selected
						checked++;
						cb.console('Optional Product is Checked');
						jQ('#optional_product_'+j+'_'+i).find('.option_loop').each(function() {
							o.push({});
							var last = o.length-1;
							o[last].options = [];
							o[last].id = i;
							jQ(this).find('.optional_product_option_'+j+'_'+i).each(function() { //get options if any
								o[last].options.push(this.value);
							});
						});
					}
				}
				if (checked != group.number_to_choose && group.number_to_choose > 0) {
					if (checked > group.number_to_choose) {
						alert('You have selected too many '+title+'. You must choose exactly '+group.number_to_choose+'.');
						return false;
					} else {
						alert('You have not selected enough '+title+'. You must choose exactly '+group.number_to_choose+'.');
						return false;
					}
				}
			}
		}
	}
	
	p[id].optional_products = o; //store optional products
	cb.console(p);
	
	try {
		addbundle_to_cart(p, function(response) {
			
		});
	} catch(err) {
		alert('cannot add items to cart in editor');
	}
	
	window.location.hash = '#';
	//dumbass colorbox
	if(status) jQ('#cboxClose').click();
}

ProductViewer.prototype.no_list_error = function() {
	this.container.html('<h1>No Products have been chosen to show here.</h1>');
}
 
ProductViewer.prototype.open_full_size_image = function(img) {
	window.open(img.split('?')[0], 'product_img_window');
}

