var product_alt = {
    
   site_url:'',
   image_url:'',
   media_url:'http://media.trophydepot.com',
   
   attribs:{},
   subgroups:{},
   
   prod_id:null,
   cart_mode:null,
   master_selects_tmp:{},
   master_selects:null,
   
   images:null,

   load:function(){
   
      var self = this;
      $(document).ready(function(){ self.init(); });
         
   },

   init:function() {
       
      var self = this;
      
      self.images = $("#selections");
      
      // get product id for later use
      var f_action = $("form[action*='/cart.php?item=']").attr('action');
      var f_regexp = /.*\/cart\.php\?item=([0-9]+)-([AUD])/;
      var f_res = f_regexp.exec(f_action);
      self.prod_id = f_res[1];
      self.cart_mode = f_res[2];
      
      self.attrib_groups = $("#options div");
      self.selects = $("#options div p select");//.attr({disabled:'disabled'});
      self.master_selects = $("#options div p select").hide();//.attr({disabled:'disabled'});
      
      self.disabled_opts = {};
      
      self.selects.each(function(){
      
         var select = $(this);
               
         var div = select.parent("p").parent("div");
         var label = div.find("label");
         
         var ready = (this.value=='') ? false : true;
         self.set_option(select.attr('name'),'ready',ready);
         
         // if an option is preselected on page load, show its image:
         if (this.value) {
            self.get_image(this.value);
         }
               
      });
      
      self.selects.each(function(){
         
         // sort out the select options and group by similar name:
                  
         var groups = {};
         var subgroups = {};
                  
         $(this).find("option").each(function(){
            
            var opt_label = $(this).html();
            var opt_arr = opt_label.split(": ");
            
            // group the options as such: {name:[attrib_id,attrib_id,etc.]}
            
            if (opt_arr.length > 1) {

               var group_name = (opt_arr.length > 1) ? opt_arr[0] : opt_label;
               if (this.value!='') {
                  if (typeof groups[group_name]=='undefined') groups[group_name] = [];
                  groups[group_name].push(this.value);
               }

            } else {

               var group_name = (opt_arr.length > 1) ? opt_arr[0] : opt_label;
               if (this.value!='') {
                  if (typeof groups[group_name]=='undefined') groups[group_name] = [];
                  groups[group_name] = this.value;
               }

            }

            
            // sort out the sub-groups (ex: "Automobiles: Antique Car"):
            
            if (opt_arr[1]) {
               if (!subgroups[opt_arr[0]]) subgroups[opt_arr[0]] = {};
               subgroups[opt_arr[0]][this.value] = opt_arr[1];
            }
            
            if ($(this).attr('disabled')) {
               self.disabled_opts[this.value] = this.value;
            }

         });
         
         self.attribs[this.name] = groups;
         self.subgroups[this.name] = subgroups;
         
      });
      
      self.add_group_selects();
      self.add_subgroup_selects();
      
      $("select.subgroup").hide();
      
      self.selects.each(function(){
      
         var select = $(this);
                                    
         select.change(function(){
            self.update_master(select.attr('name'),self.master_selects_tmp[select.attr('name')]);
            return false;
         
         });
         
         select.parents("div.option").prepend('<div class="image-preview"></div>');
         
         //console.log(select.html());
         
         if (select.attr('value')) {

            var change_event = ($.browser.msie)
               ? 'click'
               : 'change';
            select.trigger(change_event);
            self.get_image(this.value);
         }
            
      });
      
      self.set_select_defaults();
      //self.update_master();
         
   },
   
   set_option:function(attrib_id,state,value){
   
      var self = this;
      var select = $("select[name="+attrib_id+"]");
      var div = select.parent("p").parent("div.option");
   
      if (!attrib_id) return;
      if (!state) return;
   
      switch (state) {
      
         case 'ready':

            if (value) {
               div.addClass('ready');
               //self.show_next_links();
            } else {
               div.removeClass('ready');    
               //self.show_next_links(false);
            }

            break;
            
         case 'active':

            if (value) {
               div.addClass('active');
            } else {
               div.removeClass('active');               
            }

            break;
            
         case 'visible':
            
            
            break;
      
      }
   
   },
   
   set_select_defaults:function(){

      var self = this;
      
      self.selects.each(function(){
         
         if (!this.value) return;
         //if (typeof(this.value) != 'number') return;
         
         var val = this.value;
                  
         var attrib_id = this.name;
         var option = $(this).find("option[value='"+val+"']"); // hack - need to scope this down better
          
         var opt_label = option.html();
         var opt_arr = opt_label.split(": ");
         
         if (opt_arr.length > 1) {
         
            var change_event = ($.browser.msie)
               ? 'click'
               : 'change';

            var group_name = opt_arr[0];
            $("select[rel="+attrib_id+"].group").attr({value:group_name}).trigger(change_event);
            $("select[rel="+attrib_id+"].subgroup").attr({value:val}).trigger(change_event);
            self.set_option(attrib_id,'ready',val);

            self.update_master(attrib_id,val);

         }
            
      });


   },
   
   add_group_selects:function(){
   
      var self = this;
      
      for (attrib_id in this.attribs) {
            
         var attrib_groups = this.attribs[attrib_id];
         var select = $('<select rel="'+attrib_id+'" class="group"><option value="">(select)</option></select>');

         for (attrib in attrib_groups) {            

            var val = attrib_groups[attrib];
            var grouped = (typeof(val)=='object') ? true : false;
            
            if (grouped) {
                
                var group_name = attrib;
                var option = $('<option value="'+group_name+'" class="group">['+group_name+']</option>');

            } else {
    
                var disabled = (self.disabled_opts[val]==val)
                    ? ' disabled="disabled" class="disabled"' : '';
                var option = $('<option value="'+val+'"'+disabled+'>'+attrib+'</option>');

            }

            select.append(option);
                                                         
         }
   
         var att_default = self.master_selects.filter("[name="+attrib_id+"]").attr('value');
         if (!att_default) att_default = '';
         select.attr({value:att_default});

         
         var change_event = ($.browser.msie)
            ? 'click'
            : 'change';
                  
         select.bind(change_event,function(){

           // alert("CHANGE:"+this);
                                          
            var div = $(this).parents("div.option");
            var rel = $(this).attr('rel');
                                    
            var master = self.master_selects.filter("[name="+rel+"]");
            div.find("select[rel="+rel+"]").not(this).hide();
            
            // if group, need to show the group contents:
            if (isNaN(this.value) && this.value.length) {
            

               $(this).parents("div.option").find("div.image-preview img").remove();
            
               self.update_master(rel,'');
               
               var s = div.find("select").filter("[name='"+this.value+"']");
               s.attr({value:''});
               
               if (s.attr('value')=='') {
                  var nv = s.find("option").get(0).value;
                  s.attr({value:nv});
               }
               s.show();
               
               
            } else {

               if (!this.value) self.remove_image(this);
               
               if (this.value) self.set_loading_image(this,true);
               self.update_master(rel,this.value);
               
            }
         
         });
         
         /*
         if (this.value) {
            $(this).change();
            self.get_image(this.value);
         }
         */
         
         $("#options select[name="+select.attr('rel')+"]").parent("p").append(select);
      }
   
   
   },
   
   add_subgroup_selects:function(){
   
      var self = this;
  
      for (attrib_id in this.subgroups) {

          var groups = this.subgroups[attrib_id];
         
         for (name in groups) {

        
            var select = $('<select rel="'+attrib_id+'" name="'+name+'" class="subgroup"><option value="">(select)</option></select>');
            var attribs = groups[name];
            
            for (val_id in attribs) {
               var attrib_label = attribs[val_id];
               
               var disabled = (self.disabled_opts[val_id]==undefined)
                  ? '' : ' disabled="disabled" class="disabled"';
               select.append('<option value="'+val_id+'"'+disabled+'>'+attrib_label+'</option>');

            }
            
            var att_default = '';
            if (att_default=='undefined') att_default = '';
            select.attr({value:att_default}).hide();
            
            var change_event = ($.browser.msie)
                ? 'click'
                : 'change';

            select.bind(change_event,function(){

               var rel = $(this).attr('rel');

               if (!this.value) self.remove_image(this);
                              
               if (this.value) self.set_loading_image(this,true);
               self.update_master(rel,this.value);
               
            });

            $("#options select[name="+select.attr('rel')+"]").parent("p").append(select);
         
         }
      
      }
   
   
   },
   
   remove_image:function(select){

       $(select).parents("div.option").find("div.image-preview img").remove();
       return true;
   
   },
   
   set_loading_image:function(select,state){
       
       if (typeof(state)=='undefined') state = true;
       
       var theme_path = this.media_url+'/QC/themes/trophy2010/';
       var img = '<img src="'+theme_path+'loading_sm.gif" class="loading" />';
               
       if (state) {
           $(select).after(img);
       } else {
           $(select).parent().find("img.loading").remove();
       }
       
       return true;
   
   },
   
   update_attrib:function(attrib_id,val_id){

      var self = this;
      
      var ready = (val_id=='') ? false : true;
      self.set_option(attrib_id,'ready',ready);
   
   },
   
   update_master:function(attrib_id,val_id){

      var self = this;
      var master = this.master_selects.filter("[name="+attrib_id+"]");

      master.attr({value:val_id});
      
      var ready = (val_id=='') ? false : true;
      self.set_option(attrib_id,'ready',ready);
      
      var weight = this.get_weight();
      var size = this.get_size();
      
      self.get_image(val_id);
      //this.update_images();
   
   },
   
   update_images:function(){
   
      var self = this;
      //self.images.find("img").remove();
   
      num = 0;
      
      var active_ids = []; // collect IDs of all set attributes - later, retrieve their images
            
      this.master_selects.each(function(master){
      
         var master = this;
      
         var val_id = $(master).attr('value');
         var name = $(master).prev("label").text();
         var value = $(master).find("option[value="+val_id+"]").text();
         
         if (val_id) {
            num++;
            //$(".img_"+val_id).show();
            self.get_image(val_id);
            active_ids.push(val_id);
         }

         if (val_id) active_ids.push(val_id);
         
      });

      self.get_images(active_ids);
      
      if (num==0) {
         //$("#img.default").show();
      }
   
   },
   
   get_image:function(attribval_id){
      
      var self = this;
 
      if (!attribval_id) return;

      $.ajax({
         type:'GET',
         url:'/product_alt_ajax.php',
         dataType:'json',
         data:{what:'attribval_images',val_ids:attribval_id},
         success:function(json){

            var displayed = [];               
            
            var select = $("option[value="+attribval_id+"]").parent('select');
            if (!json.length) self.set_loading_image(select,false);
                                 
            for (id in json) {
               
               // make sure we don't repeat duplicate IDs:
               if (displayed[id]) continue;
               displayed[id] = 1;

               self.set_loading_image(select,false);

               var href = '/attrib_images.php?val_ids='+attribval_id;

               var img = json[id];
			

               var img_html = '<a href="'+href+'"><img src="'+img['src']+'" width="'+img['w']+'" height="'+img['h']+'" /></a>';
               //img_html += '<small><a href="'+href+'">View larger</small>';

               var img_box = $("option[value="+attribval_id+"]").parent('select').parents("div.option").find("div.image-preview");
               //img_box.hide().find("a,p").remove();
               img_box.empty();
               img_box.append(img_html).slideDown();
               img_box.find("a").click(function(){
               
                   window.open(this.href,'attribute_preview','height=400,width=400,scrollbars=no,status=no,toolbar=no,location=no');
                   return false;

               });
  
            }
         
         }
      });
   
   },
   
   get_weight:function(){
      
      var self = this;
      
      var args = {what:'product_weight'};
      if (self.cart_mode=='A') args.prod_id = self.prod_id;
      if (self.cart_mode=='U') args.item_id = self.prod_id;
      
      self.master_selects.each(function(){
         if (this.value!='') args['attribs['+this.name+']'] = this.value;
      });
      
      $.get('/product_alt_ajax.php',args,
         function(data){
            $(".weight").html(data);
         });
      
      return true;
   
   },
   
   get_size:function(){
      
      var self = this;
            
      var args = {what:'product_size'};
      if (self.cart_mode=='A') args.prod_id = self.prod_id;
      if (self.cart_mode=='U') args.item_id = self.prod_id;
      
      self.master_selects.each(function(){
         if (this.value!='') args['attribs['+this.name+']'] = this.value;
      });

      $.get('/product_alt_ajax.php',args,
         function(data){
            $(".size").html(data+'"');
         });
   
      return true;
   
   },
   
   show_next_links:function(state){
   
      if (state==undefined) var state = true;
      
      var num_empty_attribs = this.master_selects.filter("[value='']").size();
      if (num_empty_attribs==0) {
         //$("small.next").hide();
      } else {
         if (state) {
            $("small.next").show();
         } else {
            $("small.next").hide();
         }
      }
   
   },
   
   show_next_link:function(div){
   
      if (state==undefined) var state = true;
      
      var num_empty_attribs = this.master_selects.filter("[value='']").size();
      
      if (div.is(".ready")) {
      
         if (num_empty_attribs==0) {
            //div.find("small.next").hide();
         } else {
            if (state) {
               div.find("small.next").show();
            } else {
               div.find("small.next").hide();
            }
         }
      
      } else {
      
         this.show_next_links(false);
      
      }
   
   },
   
   force_show_next_link:function(div){
   
      div.find("small.next").show();
   
   }
   
}

product_alt.load();

function oc(a) {
   var o = {};
   for(var i=0;i<a.length;i++) o[a[i]]='';
   return o;
}


