String.prototype.unescapeHtml		= function(){
    var temp = document.createElement("div");
    temp.innerHTML = this;
    var result = temp.childNodes[0].nodeValue;
    temp.removeChild(temp.firstChild);
    return result;
};

var apply_special_sale_pricing		= function(options){
	var class_instance;
	class_instance	= new special_sale_pricing_class( options );
	class_instance.process_items();

	special_sale_pricing_objects.push( class_instance );
};

var special_sale_pricing_objects	= [];
var special_sale_pricing_class		= function(options){
	var $			= jQuery;
	var $this		= this;

	this.options	= options;

	this.update_NS_event_handlers = function(){
		var regex = /^syncItemPrice(\d+)$/;
		var item_id;
		var function_src;
		var cmd;
		var count = 0;
		var stringify = (typeof Function.toSource === 'function')? 'toSource' : 'toString';
		for (i in window) {
			if (
				(typeof window[i] === 'function') &&
				(item_id = regex.exec(i))
			){
				item_id			= item_id[1];
				//console.log( item_id );

				function_src	= window[i][stringify]();
				//console.log( function_src );

				function_src	 = function_src.replace(/^[(]|[)]$/g, '');
				function_src	 = function_src.substring(0, function_src.lastIndexOf('}'));
				function_src	+= ' jQuery("#itemprice' + item_id + '").triggerHandler("price_change"); }';
				//console.log( function_src );

				//cmd = 'window["' +i+ '"] = ' + function_src;
				cmd = 'window["' +i+ '"] = ' + function_src.replace(i, '') + ';';
				//console.log( cmd );

				eval( cmd );
				//console.log( window[i].toSource() );

				count++;
			}
		}
		return count;
	};

	this.add_DOM_polling = function(items){
		setInterval(
				function(){
					$.each(items, function(i){
						var PC = items[i].price_container;
						if (PC.find('.promo_price').length === 0) {
							PC.triggerHandler("price_change");	//update
						}
					});
				},
				3000
		);
	};

	this.searchArray = function(needle, haystack, case_insensitive) {
		if (typeof(haystack) === 'undefined' || !haystack.length) return -1;
		
		var high = haystack.length - 1;
		var low = 0;
		case_insensitive = (typeof(case_insensitive) === 'undefined' || case_insensitive) ? true:false;
		needle = (case_insensitive) ? needle.toLowerCase():needle;
		
		while (low <= high) {
			mid = parseInt((low + high) / 2)
			element = (case_insensitive) ? haystack[mid].toLowerCase():haystack[mid];
			if (element > needle) {
				high = mid - 1;
			} else if (element < needle) {
				low = mid + 1;
			} else {
				return mid;
			}
		}

		return -1;
	};

	this.process_items = function(){
		var set				= $.merge( $('.listItem[id]'), $('.customizer[id]') );
		var ndash			= '&ndash;'.unescapeHtml();
		var found_sku_list	= [];

		$.getJSON(
			$this.options.json_file,
			function(json_data){
				if (json_data.length > 0) {

					set.each(function(){
						var item_container	= $(this);
						var sku				= item_container.attr('id');

						$.each(json_data, function(i){
							var index;
							var sorted_sku_list = json_data[i]['skus'];
							if (sorted_sku_list.length > 0){
								index = $this.searchArray(sku, sorted_sku_list, false);
								if (index !== -1) {
									found_sku_list.push( {"label":json_data[i]['label'], "item_container":item_container, "sku":sku} );
									return false; // break inner loop
								}
							}
						});
					});

					if (found_sku_list.length > 0) {
						$.each(found_sku_list, function(i){
							var found_sku_item = found_sku_list[i];
							var price_container = found_sku_item.item_container.find('.sale_price, .itemPrice, #online_price').find('span:not(.itemprice):last');
							price_container.bind("price_change", function(){

								var container		= found_sku_item.item_container.find('.listItemPrices, .displayPrices').first();
								var nonsale_price	= container.find('.nonsale_price, .was_price').text();
								var sale_label		= found_sku_item.label + ' ';
								var sale_price		= container.find('.sale_price, .itemPrice, #online_price').find('span:first').text();

								var is_onsale		= function(){
															var regex_pattern	= /[^0-9\.]/g;
															var f_sale_price	= parseFloat(    sale_price.replace(regex_pattern, '') );
															var f_nonsale_price	= parseFloat( nonsale_price.replace(regex_pattern, '') );
															return (
																(isNaN(f_sale_price))		||
																(isNaN(f_nonsale_price))	||
																(f_sale_price >= f_nonsale_price)
															)? false : true;
													  };

								if (
									(
										(typeof $this.options.override === 'object')	&&
										($this.options.override !== null)				&&
										($this.options.override.onsale)
									) || is_onsale()
								){
									var nonsale_color	= '#888888';
									var sale_color		= '#990000';
									var html_block;
									if (
										(typeof $this.options.override === 'object')	&&
										($this.options.override !== null)				&&
										(typeof $this.options.override.html_block === 'string')
									){
										html_block	= $this.options.override.html_block;
										html_block	= html_block
														.replace(/{{nonsale_color}}/g, nonsale_color)
														.replace(/{{nonsale_price}}/g, nonsale_price)
														.replace(/{{sale_color}}/g, sale_color)
														.replace(/{{sale_label}}/g, sale_label)
														.replace(/{{sale_price}}/g, sale_price)
										;
									}
									else {
										// default
										html_block	= '<span style="color:' +sale_color+ ';text-decoration:line-through"><span style="color:' +nonsale_color+ '">' +nonsale_price+ '</span></span><span style="color:' +sale_color+ ';text-transform:uppercase;white-space:nowrap;padding-left:8px;">' +sale_label +sale_price + '</span>';
									}

									if (found_sku_item.item_container.find('#special_price_container').length === 0) {
										container.hide();
										$('<div></div>').attr('id','special_price_container').append(html_block).insertAfter(container).css('white-space','nowrap').css('marginTop','15px');
									}
									else {
										found_sku_item.item_container.find('#special_price_container').empty().append(html_block);
									}
								}

								$(this).append( $('<div></div>').attr('class','promo_price') );	// presence of selector tells polling function to NOT fire "price_change" event
							});
							price_container.triggerHandler("price_change");	//initialize
							found_sku_list[i]['price_container'] = price_container;
						});
					}

				}
				if (typeof $this.options.callback === 'function') {
					$this.options.callback(found_sku_list);
				}
			}
		);
	};

	this.options.callback = function(items) {
		if (
			(items.length > 0)								&&
			(typeof $this.options.callbacks === 'object')	&&
			($this.options.callbacks !== null)				&&
			(typeof $this.options.callbacks.initialize === 'function')
		){
			$this.options.callbacks.initialize();
		}

		if (
			(items.length > 0) &&
			($this.update_NS_event_handlers() === 0)
		){
			$this.add_DOM_polling(items);
		}
	};
};
