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();
        
    },
    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();
		var doalerts = u.getData('debugme');
		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(response) { response = JSON.decode(response); }
	        		        	
	        	var new_string = "";
	        	
	        	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('(');
		        				upd = cur_val[0].clean() + " (" + stok + " in stock)";
		        			} 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) {
		        				new_string += '<option value="' + cur_val2.clean() + '" selected="selected"> ' + upd.clean() + '</option>';
		        			} else {
		        				new_string += '<option value="' + cur_val2.clean() + '"> ' + upd.clean() + '</option>';
		        			}
		        			dc++;
		        		}
		        			
		        	});
		        	
		        	$('swatch').empty();
		        	$('swatch').set('html', new_string);	
	        	}
	        	
	        	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});
        }        
    },
    first_update:true,
    updateOptions: function() {

                var u = new URI();
                var doalerts = u.getData('debugme');
        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;               
                
		// AA
		if(stock_level > 96) { stock_level = 96; }

                varimage = response.instance_properties.var_image;
                
                vartitle = response.instance_properties.ebay_exact_colour;
                if(vartitle && vartitle.contains(':')) {
                	vartitle = vartitle.split(':');
                	if(vartitle.length) {
                		vartitle = vartitle[1];
                	}
                }
                if(!vartitle || vartitle == '') {
                	vartitle = response.instance_title;
                }                
                
                if(instance_id) { $('instance_id').value = instance_id; }
                if(price) { $('price').value = price; }
                
                // console.log(productOptions.first_update);
                if(!productOptions.first_update) {
                	// console.log('Do update image');
                	// console.log("Checking for image " + varimage);
	                if(varimage && varimage !=='') {
	                	// console.log('Have image');
	                	if(varimage) { $('var_image').src = 'http://cdn.sockshop.co.uk/cms_media/images/' + varimage; }
	                } else {
	                	// console.log('Missing Image');
	                }
                } else {
                	// console.log('Do not update image');
                	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();
            }
        }).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() {
        $('addtobasket').disabled = 1;
        $('addtobasket').addClass('adddisabled');
    },
    stopPleaseWait: function() {
    },
    optionNotAvailable : function() {
    	this.first_update = false;
        $('addtobasket').disabled = 1;
        $('addtobasket').addClass('adddisabled');
        $('addtobasket').value = 'Select Options';
        $('instance_id').disabled = true;
    },
    optionAvailable : function() {
    	this.first_update = false;
        $('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() { optionsManager = new productOptions(); });
