(function($){
	jQuery.fn.extend({
		image_url: Array(),
		
        BandOptions: function() {
            $().init_options('pre');
        },
        
        init_options: function() {
            var obj = options;
            var str = '';
			for ( i in obj ) {
                if(get_price_button_clicked || (obj[i].which == "pre")) {
                    if(obj[i].group != undefined) {
                        str += $().get_options_html(i, obj[i]);
                    }
                    else {
						if ( obj[i].type == group_type_width) {
							str += $().get_text_html(i, obj[i], init_width);
							user_values[i] = init_width;
						} else if ( obj[i].type == group_type_height) {
							str += $().get_text_html(i, obj[i], init_height);
							user_values[i] = init_height;
						} else {
	                        str += $().get_text_html(i, obj[i]);
						}
                    }
                }
            }
            $("#OptionsPre").html(str);
			
			// init thick box
			tb_init('a.inchcovert');
        },
        
        get_price: function() {
			// check all fields displayed so far filled in
			var is_valid = true;
			$("#OptionsPre input").each(function() {			
				if(!$(this).val()) {
					// @TODO: error
					is_valid = false;
				}
			});
			$("#OptionsPre select").each(function() {
				if(!$(this).val() || $(this).val() == "null") {
					// @TODO: error
					is_valid = false;
				}
			});
			// @TODO: report errors
			if(!is_valid) { return false; }
            get_price_button_clicked = true;
            // regenerate any "unfiltered" data
            $().select_option_loop(options);
           
            // apply any filtering needed
            $().apply_filters();
			
			// get the price
			$().get_price_ajax();
			return true;
        },
        
		/**
		 * get_price_ajax()
		 * Actually gets the price from the server
		 */
		get_price_ajax: function() {
			if(get_price_button_clicked) {
				// check the size if necessary
				if(!$().check_sizes()) {
					$().throw_error("The size you have specified is not within the parameters");
					$("#buy_button").hide();
					$("#pricedata").hide();
					return;
				}

				$().hide_error();
				
				$("#pricedata").html("<p>Please wait...</p>");
				$.ajax({
					type: "POST",
					url: "/ajax/blinds/",
					data: $("#ProductOptions").serialize()+"&c=get_price_html",
					dataType: "html",
					success: function(html) {
						$("#pricedata").html(html);
						$("#pricedata").show();
						
						$().show_hide_buy_button();
					}
				});
			}
			
			// init thick box
			tb_init('a.inchcovert');
		},
		
		show_hide_buy_button: function() {
			var is_valid = true;
			$("#OptionsPre input").each(function() {		
				if(!$(this).val()) { is_valid = false; }
			});
			$("#OptionsPre select").each(function() {
				if(!$(this).val() || $(this).val() == "null") { is_valid = false; }
			});
			if(is_valid) {;
			//	$("#buy_button").show();
			}
			else {
				$("#buy_button").hide();
				$("#buy_button_off").show();
			}
		},

		
		buy_product: function() {
			if(!get_price_button_clicked) { return false; }
			if($().get_price()) {
				return true;
			}
			return false;
		},
		
		check_sizes: function() {
			// this product does not have any sizes to worry about
			if(sizes['height_min'] == undefined) { return true; }
			if(!$("#sgroup103").length) { return true; }
			if(!$("#sgroup104").length) { return true; }
			// hack!
			var width = $("#sgroup103").val();
			var height = $("#sgroup104").val();
			min_check = max_check = max_turned_check = false;
			
			if(width >= eval(sizes["width_min"]) && height >= eval(sizes["height_min"])) {
				min_check = true;
			}
			if(width <= eval(sizes["width_max"]) && height <= eval(sizes["height_max"])) {
				max_check = true;
			}
			if(sizes["height_max_turned"]) {
				if(width = eval(sizes["width_max_turned"]) && height <= eval(sizes["height_max_turned"]) ) {
					max_turned_check = true;
				}
			}
			//else { max_turned_check = true; }
			//alert ('in cehck sizes function height ='+height+', width='+width+' width_max="'+sizes['width_max']+'" height_max ="'+sizes['height_max']+'" max_turned_check='+max_turned_check+' max_check='+max_check+' min_check='+min_check);

			return min_check && (max_check || max_turned_check);
		},
		
        /**
         * change_text_value()
         * Called whenever a text input field is changed
         * Applies any filtering based on the values of all fields
         */
        change_text_value: function(f) {
            var id = f.name;
            value = f.value;
            user_values[id] = value;
            
            // regenerate any "unfiltered" data
            $().select_option_loop(options);
            
            // apply any filtering needed
            $().apply_filters();
            
            // focus
            $("#s"+id).focus();
			
			$().get_price_ajax();
        },
        /**
         * select_option_from_form()
         * Called whenever a select box input field is changed
         * Generates and displays new fileds based on selection
         * Applies any filtering based on the values of all fields
         */
        select_option_from_form: function(f) {
            id = f.name;
            value = f.options[f.selectedIndex].value;

            // set the value for this select/option, store this in a flat array
            user_values[id] = value;
            
            // set all options to class="remove-element"
            $("[id^='g']").addClass("remove-element");
            
            // loop through all options, adding as needed
            $().select_option_loop(options, 0, id);
			
            // remove all elements with class="remove"
            $(".remove-element").each(function(){
                $(this).remove();
                // not forgetting to remove assigned values from the user array
                id = $(this).attr('id');
                delete user_values[id];
            });
            
            // finally, apply any filtering
            $().apply_filters();
			
			$().get_price_ajax();
        },
        select_option_loop: function(obj, parent_id, selected_id) {
            if(obj == undefined) { return false; }
            if(parent_id == undefined) { parent_id = 0; }
			if(selected_id == undefined) { selected_id = 0; }
            
			$().image_url = Array();

            for ( i in obj ) {
                // if is a select option, get children
                if(user_values[i] != undefined && user_values[i] != "null") {
                    if(obj[i].group != undefined) {
                        html = $().get_options_html(i, obj[i], user_values[i]);
                        $("#"+i).replaceWith(html);
                        // get the children
                        child_group = eval("obj[i].group."+user_values[i]+".group");
                        if(child_group != undefined) {
                            $().select_option_loop(child_group, i);
                        }
                    }
                    else {
                        //html = $().get_text_html(i, obj[i], user_values[i]);
                        //$("#"+i).replaceWith(html);
                    }
                    $("#"+i).removeClass("remove-element");
                    

                    
                }
                else if(parent_id == 0) {
                    $("#"+i).removeClass("remove-element");
                    // regenerate this incase of filtering
                    can_display_this = false; 
                    if(get_price_button_clicked) { can_display_this = true; }
                    else if(obj[i].which == "pre") { can_display_this = true; }
                    
                    if(can_display_this) {
                        if(obj[i].group != undefined) {
                            html = $().get_options_html(i, obj[i], user_values[i]);
                        }
                        else {
                            html = $().get_text_html(i, obj[i], user_values[i]);
                        }
                        if($("#"+i).length > 0) {
                            $("#"+i).replaceWith(html);
                        }
                        else {
                            $("#OptionsPre").append(html);   
                        }
                    }
                }
                else {
                    if($("#"+i).length > 0) {
                        $("#"+i).removeClass("remove-element");
                    }
                    else {
                        $("#"+parent_id).after($().get_options_html(i, obj[i]));
                    }
                }
				
				// add any popup or image details
				for(gp_id in $().image_url) {
					$().add_image(gp_id, $().image_url[gp_id]);
				}
            }
        },
        /**
         * apply_filters()
         * Gets and applies all filters based on the values within any text input,
         * removes any elements that are filtered out
         */
        apply_filters: function() {
            // get all text input fields
            values = new Array();
            $("[id^='g'] :text").each(function() {
                id = $(this).attr('name');
                if(id != undefined) {
                    values[id] = $(this).val();    
                }
            });
            
            // get the filters
            filter_array = new Array();
            for ( i in filters ) {
                filter_count = 0;
                for( j in filters[i].filter ) {
                    for( k in values ) {
                        if(k == j) {
                        	// bug fix - convert to numerical data
                        	values[k] = values[k] * 1;
                        	filters[i].filter[j] = filters[i].filter[j] * 1;
                            if(values[k] == undefined) { values[k] = 0; }
                            if(filters[i].gtlt == "gt" && (values[k] >= filters[i].filter[j])) {
                                filter_count += 1;
                            }
                        }
                    }
                }
                if(filters[i].filter_count == filter_count) {
					// if option_id, remove just the option,
					if(filters[i].option_id != undefined) {
						$(".f-option"+filters[i].option_id).remove();
						delete user_values["option"+filters[i].group_id];
					}
					// otherwise remove whole group
					else {
						$(".f-group"+filters[i].group_id).remove();
						delete user_values["group"+filters[i].group_id];
					}
                }
            }
        },

        /**
         * get_text_html()
         * generates the html for a text input field
         * @returns html string
         */
        get_text_html: function(id, obj, value) {
            if(obj == undefined) { return false; }
            if(value == undefined) { value = ''; }
            str = '<p id="'+id+'" class="optionsp f-'+id+'"><label class="texthold">'+obj.name+'</label>'+
                '<input class="textfield1"s id="s'+id+'" type="text" name="'+id+'" title="'+obj.name+'" value="'+value+'" onkeyup="$().change_text_value(this);" tabindex="10"/>';
			// this is the place to add any popup urls
			str += $().get_popup_html(id, obj.popup_url);
			// bit of a hack
			if(id == "group103") {
				str += '<a href="#TB_inline?inlineId=InchesConvertor" class="inchcovert">Inches converter &raquo;</a>';
			}
			str += '</p>';
            return str;
        },
        /**
         * get_options_html()
         * generates the html for a select options field
         * @returns html string
         */
        get_options_html: function(id, obj, value) {
            if(obj == undefined) { return false; }
            if(value == undefined) { value = ''; }
			
            str = '<p id="'+id+'" class="optionsp f-'+id+'"><label class="texthold">'+obj.name+'</label>'+
                '<select class="dropper1" id="s'+id+'" name="'+id+'" title="'+obj.name+'" onchange="$().select_option_from_form(this);" tabindex="10"><option value="null">Please select...</option>';
            for ( j in obj.group ) {
                str += '<option value="'+j+'" class="f-'+j+'" ';
                if(value == j) {
					str += 'selected="selected"';
					// save any images for inserting
					$().image_url[id] = obj.group[j].image_url;
				}
                str += '>'+obj.group[j].name+'</option>';
            }
            str += '</select>';
			// this is the place to add any popup urls
			str += $().get_popup_html(id, obj.popup_url);
			str += '</p>';
            return str;
        },
		
		/**
		 * Appends any images, or popup url links to the input fields
		 */
		add_image: function(id, url) {
			$("#info-"+id).remove();
			if(url == undefined || url == '') { return; }
			$("#"+id).append('<img id="info-'+id+'"src="/static/images/products/info/'+ url+'" alt="" />');
		},
		get_popup_html: function(id, url) {
			// add popup url in
			if(url == undefined || url == '') { return ''; }
			/*
			str = '<a id="info-'+id+'" href="javascript:;" class="moreinfo" onclick="window.open(\''+
				url+'\', \'popup\', '+
				'\'toolbar=0,location=0,directories=0,status=0,'+
				'menubar=0,scrollbars=1,resizable=1,maximize=0,width=520,height=450\')'+
				'">More Info &raquo;</a>';
			*/
			str = '<a href="javascript:;" onclick="window.open(\''+
				url+'\', \'popup\', '+
				'\'toolbar=0,location=0,directories=0,status=0,'+
				'menubar=0,scrollbars=1,resizable=1,maximize=0,width=520,height=450\')'+
				'" class="questionmark" title="More Info &raquo;"><img src="/static/images/questionmark_icon.jpg" alt="" /></a>';
			return str;
		},
		
		/**
		 * Error and Notification message functions
		 */
		throw_error: function (e) {
			$("#pricedata").hide();
			$("#buy_button").hide();
			$("#ErrorMsg").html("<strong>Error:</strong> "+e);
			$("#ErrorMsg").show();
		},
		hide_error: function() {
			$("#ErrorMsg").hide();
		}
    })
})(jQuery);