var optionsManager = false;
var productOptions = new Class({
    Implements: [Options, Events],
    options:{
        fields: ['size', 'swatch'],
        stockSelectId: 'swatch'
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.attachChangeEvents();
        
        this.first_run = true;
        
        this.getInitialStockTotals();
        
    },
    
    first_update:true,    
    
    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;
		var u = new URI();

		this.requestObject = new Request({
	        url: url, 
	        method:'post',
	        link: 'chain',
	        onFailure: function() { that.updateOptions(); },
	        onSuccess: function(response) {
	        
	        	var dc=0;  

	        	that.myswatch_options = $('swatch').getChildren('option');
	        	that.mysize_options = $('size').getChildren('option');
	        	
	        	if(that.first_run) {
                    that.cur_select = $('swatch').selectedIndex;	
                }      
	        	        
	        	if(response) { response = JSON.decode(response); }

	        	if(response.length) {

		        	response.each(function(row, rind) {

                        var theindex = rind + 1;

                        if(response.length == 1 && that.myswatch_options.length == 1) { 
                            theindex = rind; 
                        }
                        
                        var currentOption = that.myswatch_options[theindex];
                        
                        if(currentOption) {
                            var stockLevel = row.stock;
                            
                            if(!stockLevel) { 
                                stockLevel = 0; 
                            } else if(stockLevel>96) { 
                                stockLevel=96; 
                            }       
                            
                            var optionText = currentOption.get('text');
                            optionText = optionText.split('(')[0];
                            
	        				if(stockLevel == 'Not Stocked'){
	        					currentOption.set('text', optionText.clean() + " (not stocked)");
	        				} else if(stockLevel > 0){
	        					currentOption.set('text', optionText.clean() + " (" + stockLevel + " in stock)");
	        				} else {
	        					currentOption.set('text', optionText.clean() + " (0 in stock) - Click to Email Me");
	        					currentOption.set('rel', 'nostock');
	        				}

                        }
		        	});	
	        	}
	        	
	        	if(dc == 1) {
	        		$('swatch').options.selectedIndex = 0;
	        	}
	        	
				if(that.mysize_options.length == 2) {
					that.mysize_options[0].destroy();
					$('size').selectedIndex = 0;
				}
				
				if(!that.first_run) {		        	
	            	that.updateOptions();	
	        	} else {
	        	
	        		if($('size').selectedIndex == 0 && $('swatch').selectedIndex == 0) {
	        			that.updateOptions();
	        		}
	        	
	        		that.first_run = false;
	        	}
	        }
	    });
	    
		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) {
				//if(ind > 0) {
					var v = el.get('value');
					// var v = that.myswatch_options[ind].get('value');
					if($chk(v) && v.clean() !=='') {
						myObj[ic] = {size: escape(mysize),
									  swatch: escape(v),
									  stock: 0};
						ic++;
					}	
				//}
			});
			
			myObj = JSON.encode(myObj);
			
			// alert(myObj);
			this.requestObject.send({data: "jsond=" + myObj});
        }        
    },
    
    updateOptions: function() {

        var u = new URI();
        var params = '';
        var url    = this.getUrl();
        var size_el = $('size');
        var mysize = size_el.get('value');

        if(!mysize) {
            mysize = size_el.getChildren('option')[1].get('value');
        }
        mysize = mysize.replace(/\+/, '%2B');
        
        var swatch_el = $('swatch');
        var siz = mysize;
        var swa = swatch_el.get('value');
        var newparams = "size=" + escape(siz) + "&swatch=" + escape(swa);
        var productOptions = this;
        var jsonRequest = new Request({
            url: url + '/index.html:ajaxCombiJson?'+newparams, 
            onRequest: function() { productOptions.startPleaseWait(); },
            onComplete: function(response, responseXML){
            
                var instance_id = false;
                var stock_level = 0;
                var price       = false;
                var varimage    = false;
                
            	if(typeof response == 'undefined' || !$chk(response)) { 
            		productOptions.optionNotAvailable(); return false; 
            	}
            	
            	response = JSON.decode(response);

            	instance_id = response.instance_id;
            	if(typeof instance_id == 'undefined' || !$chk(instance_id)) { 
            		productOptions.optionNotAvailable(); return false; 
            	}
            	
				price       = response.instance_properties.price;
				stock_level = response.instance_properties.stock_level;               
                
        		if(stock_level > 96) { 
                    stock_level = 96; 
                }

                varimage = response.instance_properties.var_image;
                
                vartitle = response.instance_properties.swatch;
                if(vartitle && vartitle.contains(':')) {
                	vartitle = vartitle.split(':');
                	if(vartitle.length) {
                		vartitle = vartitle[1];
                	}
                }

                vartitle = vartitle.replace('No Swatch', '');
                vartitle = vartitle.replace('N/S', '');
                vartitle = vartitle.replace('n/s', '');
                if(!vartitle || vartitle == '') {
                	vartitle = response.instance_title;
                }                
                
                if(instance_id) { 
                    $('instance_id').value = instance_id; 
                }
                
                if(price) { 
                    $('price').value = price; 
                }
                
                if(!productOptions.first_update) {
	                if(varimage && varimage !== '') {
	                	if(varimage) { 
	                	  $('var_image').src = 'http://cdn.sockshop.co.uk/cms_media/images/' + varimage; 
                        }
	                }
                } else {
                	productOptions.first_update = false;
                }
                
                if(!$chk(stock_level)) { 
                    stock_level = 0; 
                }

                if($('dynamic_swatch_title')) {
                	if(!vartitle) { vartitle = ''; }
                	$('dynamic_swatch_title').addClass('bi-s');
                	$('dynamic_swatch_title').set('html', vartitle);
                }
                
                productOptions.optionAvailable();
                productOptions.stopPleaseWait();
                
                if(stock_level == 0) {
                    productOptions.optionNoStock(response);
                }                  
            }
        }).get();      
    },
    
    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() {    
    },
    
    stopPleaseWait: function() {
    },
    
    optionNoStock: function(obj) {
        colour = obj.instance_properties.swatch.split(':')[1];
        colour = colour.replace('No Swatch', '');
        
        $('saProductColour').set('html', colour);
        $('saProductSize').set('html', obj.instance_properties.size);
        $('saProductPrice').set('html', obj.instance_properties.price);
        
        image = 'http://cdn.sockshop.co.uk/cms_media/images/75x75_fitbox-';
        
        
        if(obj.instance_properties.var_image && obj.instance_properties.var_image != 'null') {
            $('saProductImage').src = image + obj.instance_properties.var_image;
        }

        $('stockalertemailinstanceid').value = obj.instance_id;
        stockbox = new MultiBox('stockalertlink', {useOverlay: false, showControls: false});    
        stockbox.open($('stockalertlink'));   
        
        $('swatch').selectedIndex = 0;       
    },    
    
    optionNotAvailable : function() {
    	this.first_update = false;
        $('instance_id').disabled = true;
    },
    
    optionAvailable : function() {
    	this.first_update = false;
        $('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() { optionsManager = new productOptions(); });


function checkSizeSwatch() {
        var s = $('size').get( 'value' );
        var c = $('swatch').get( 'value' );
        
        if(s == '' && c == '') {
                alert('Please select a size & colour before adding to basket.');
                return false;   
        }
    
        if(s == '' ) {
                alert( 'Please select a size before adding to basket.' );
                return false;
        }
        
        if(c == '' ) {
                alert( 'Please select a colour before adding to basket.' );
                return false;
        }
        
        if($('instance_id').get( 'value' ) == '') {
                return false;
        }
    
        return true;
}

