var optionsManager2 = false;
var productOptions2 = new Class({
    Implements: [Options, Events],
    options:{
        fields: ['size', 'swatch'],
        stockSelectId: 'swatch'
    },
    initialize: function(options){
        this.setOptions(options);
        this.attachChangeEvents();
        this.getInitialStockTotals();
    },
    attachChangeEvents: function() {
        var that = this;
        for(i=0,l=this.options.fields.length;i<l;i++) {
            if(element = $(this.options.fields[i])) {
                element.addEvent('change', function(e) {
                
                	that.cur_select = $('swatch').selectedIndex;
                	that.getInitialStockTotals();
                });
            } 
        }
    },
    getInitialStockTotals:function() {
		var url = this.getUrl();
		var that = this;

		this.requestObject = new Request({
	        url: url, 
	        method:'post',
	        link: 'chain',
	        onRequest: function() {
	        },
	        onFailure: function() {	        	          
	        },
	        onSuccess: function(response) {
	        	   
	        	var dc=0;  
	        		        	        
	        	that.myswatch_options = $('swatch').getChildren('option');
	        	that.mysize_options = $('size').getChildren('option');
	        
	        	if(response) { response = JSON.decode(response); }

	        	var new_string = "";
	        	
	        	var hasStock = false;
	        	
	        	if(response.length) {
		        	var fel = that.myswatch_options[0];
		        	var fval = fel.get('value');
		        	var fopt= fel.get('text');
		        	
		        	if(response.length > 1 && response[0]['size'] && response[0]['swatch']) {
		        		new_string = "<option value='" + fval + "'>" + fopt + "</option>";
		        	}
		        	
		        	response.each(function(row, rind) {

                                        var theindex = rind + 1;

                                        if(response.length == 1 && that.myswatch_options.length == 1) { theindex = rind; }
                                        var hopefully_the_correct_option = that.myswatch_options[theindex];                                   $

                                        if(hopefully_the_correct_option) {

                                                var stok = row.stock;
                                                if(!stok) { stok = 0; }
                                                if(stok>96) { stok=96; }
                                                var upd = false;
                                                var cur_val = hopefully_the_correct_option.get('text');
		        			if(theindex > 0) {
		        				cur_val = cur_val.split('(');
		        				if(stok == 'Not Stocked'){
		        					upd = cur_val[0].clean() + " (not stocked)";
		        				} else if(stok > 0){
		        					upd = cur_val[0].clean() + " (" + stok + " in stock)";
		        					hasStock = true;
		        				} else {
		        					upd = cur_val[0].clean() + " (0 in stock) - Email Me";		        				
		        				}
		        			} else {
		        				upd = cur_val.clean();
		        			}
		        			var cur_val2 = hopefully_the_correct_option.get('value');
		        		}
		        		if(typeof upd !=='undefined') {
		        			if(that.cur_select && theindex == that.cur_select && hasStock) {
		        				new_string += '<option value="' + cur_val2.clean() + '" selected="selected"> ' + upd.clean() + '</option>';
		        			} else {
		        				new_string += '<option value="' + cur_val2.clean() + '"> ' + upd.clean() + '</option>';
		        			}
		        		}
		        	});
		        	$('swatch').empty();
		        	$('swatch').set('html', new_string);	
	        	}
	        		
	        	var skids= $('size').getChildren('option');
				if(skids.length == 2) {
					skids[0].destroy();
				}

	        	if(dc == 1) {
	        		$('swatch').options.selectedIndex = 0;
	        	}
	        	
				if(that.mysize_options.length == 2) {
					that.mysize_options[0].destroy();
					$('size').selectedIndex = 0;
				}

                if(hasStock == false) {
                    $('swatch').addEvent('change', function(e, obj) {
                        if($('swatch').selectedIndex > 0) {
                            $('stockalertemailinstanceid').value = $('instance_id').value;
                            stockbox = new MultiBox('stockalertlink', {useOverlay: false, showControls: false});    
                            stockbox.open($('stockalertlink'));  
                        }
                        
                        $('swatch').selectedIndex = 0;                        
                    });                    
                }

	            // that.updateOptions();
	        }
	    });
	    
		this.swatchselector = $(this.options.stockSelectId);
		if(this.swatchselector) {
			var myObj = [];
			var mysize_el = $('size');
			if(!mysize_el) { return false; }
			var mysize = mysize_el.get('value');
			if(!mysize) {
				mysize = mysize_el.getChildren('option')[1].get('value');
			}
			
			mysize = mysize.replace(/\+/, '%2B');
			
			var myswatch_el = $('swatch');
			if(!myswatch_el) { return false; }
			
			this.myswatch_options = myswatch_el.getChildren('option');
			if(!this.myswatch_options || !this.myswatch_options.length) { return false; }
			
			var ic=0;
			this.myswatch_options.each(function(el, ind) {
				var v = el.get('value');
				if($chk(v) && v.clean() !=='') {
					myObj[ic] = {size: escape(mysize),
								  swatch: escape(v),
								  stock: 0};
					ic++;
				}	
			});
			
			myObj = JSON.encode(myObj);

			this.requestObject.send({data: "jsond=" + myObj});
        }
    },
    in_array: function(needle, haystack, strict) {
        var found = false, key, strict = !!strict;
        for (key in haystack) {
            if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
                found = true;
                break;
            }
        }
        return found;
    },
    startPleaseWait: function() {
        $('addtobasket').disabled = 1;
        $('addtobasket').addClass('adddisabled');
    },
    stopPleaseWait: function() {
    },
    optionNotAvailable : function() {
        $('addtobasket').disabled = 1;
        $('addtobasket').addClass('adddisabled');
        $('addtobasket').value = 'Please Select Options';
        $('instance_id').disabled = true;
    },
    optionAvailable : function() {
        $('addtobasket').disabled = 0;
        $('addtobasket').removeClass('adddisabled');
        $('addtobasket').value = 'Add to Basket';
        $('instance_id').disabled = false;
    },    
    getUrl: function() {
        path = document.location.pathname.toString().replace(/:edit/, '');
        host = document.location.host.toString();
        prot = document.location.protocol.toString();
        return prot + '//' + host + path;
    }
});
window.addEvent('domready', function(){
    optionsManager2 = new productOptions2();    
});

function checkSizeSwatch() {
        return true;
}
