/*
 * script to identify seasonal coffees added to club order, open modal dialogue to select a default, ajax to create dropdown, add the default coffee to the main form, submit the main form
 */


var s = new seasonal;
var api = null;

function startSeasonal(){

  



   $("input.isseasonal").each(function(){
       var mainform = $(this).parents('form');
       var $this = this;
       if($($this).val() == 'Y')
       {
          
           $("#btn_addtoclub").click(function(){
               s.run(mainform,true);
               return false;
           });
       }
   });

   $("select.coffeeselection").change(function(){
         var mainform = $(this).parents('form');
         var $this = this;
         s.runClub(mainform,this,true);
         return false;
   });


}



function seasonal()
{
    this.form = null;
    this.selections = null;
    this.api = null;
    this.code = null;
    this.select = null; //for club offer
    this.api = null;
    this.type = null;
    this.productId = null;
    this.descriptions = null;
    this.tiphtml = null;
    this.size = '8.0 oz';


    this.init = function(form,modal,type)
    {
      //  this.api = $("#modal_seasonal").overlay({api:true});
        if(modal) this.api = api;
        this.form = form;
        if(type!=null) this.type = type;
        this.setProductId();

    }

    this.run = function(form,modal,type){
        this.init(form,modal,type);
        this.setSelections();
        return false;
    };

     this.runClub = function(form,select,modal){
        this.select = select;
        var selection = $(select).val();
        var option = $("option[value='"+selection+"']");
        this.init(form,modal);
        if(option.parent('optgroup').attr('label')=='SeasonalCoffees')  {
            this.setSelections();
            $(select).prev().val('140');
        }
        else
            {
                this.clearAlternate();
                $(select).prev().val('');
            }
        return false;
    };

    this.runMyAccount = function(form,select)
    {
        this.init(form,null,'myaccount');
        this.setSelections();
    }

    this.setProductId = function(){ //sets the product id so we can get the available dates
        if(this.select==null) this.productId = $(this.form).find("input[name='productId']").val();
        else this.productId = $(this.select).val();

       //debug(this.productId)
    }

    this.setDropdown = function(){  //creates dropdown for my account page
       var $this = this;
    //   console.log($this.size)
       $this.code = '<li><label>Choose an alternate: <img class="help" src="/resources/images/2009/help_r.gif" alt="This coffee is only offered for a limited time. Please select an alternative coffee to replace this selection in your home delivery schedule when its production ends (you can login to your account to change your selection at any time)." /></label><select name="altSelection" id="altSelection">';
       $this.code+='<option value="140">Boca Sunrise Coffee - 8 oz.</option>';
       for(i in this.selections)
        {

            if(i!='Seasonal') $this.code +='<optgroup label="'+i+'">';
            for(j in this.selections[i])
            {
                 if(i!='Seasonal')
                     {
                        if(!this.selections[i][j].name.match(/baby/gi)) 
                         $this.code+='<option value="'+this.selections[i][j].id+'">'+this.selections[i][j].name+'</option>';
                       
                    }
            }
             $this.code+='</optgroup>';
        }
         $this.code+= '</select></li>';
         $("#response_seasonal").empty().append($this.code).show();
         makeBasicOmnitip('.help','alt');
}

    this.setSelections = function()
    {
        var $this = this;
        if(this.selections == null)
        {
        var d = getDomain();
        var p = {};
        $this.size = $(this.form).find("li.size").html();
        if($this.size == null) $this.size = $("span.size").html();
        if($this.size == null && $this.select!=null)
            {
                var prod = $($this.select).html();
                if(prod.match(/2 oz/)) $this.size = '2.0 oz';
                else $this.size = '8.0 oz';
            }
        $.ajax({
                        url: d+'/clubProductsAjaxAction.do',
                        data:p,
                        type:'GET',
                        dataType: 'jsonp',
                        success: function (data, textStatus) {
                            $this.selections = data;
                            $this.getSelections();
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            debug(errorThrown);
                           // $("#modal_content .login_alerts").append('<div class="alert">Login is unsuccessful.  Please try again.</div>');
                        },
                        beforeSend: function (XMLHttpRequest) {
                        
                          //   $("#modal_content").append('<div class="loading" style="top:48%;left:48%;"><img src="/bocajava/images/2009/loading_small.gif" /></div>');
                        },
                        complete: function (XMLHttpRequest) {
                           //  $("#modal_content .loading").remove();
                        }
         });
        }
        else $this.getSelections();
    }

    this.getSelections = function()
    {
        if(this.type=='myaccount') this.setDropdown();
        else this.parseSelections();
    }

    this.parseSelections = function()
    {

        var $this = this;



       
        var html='<option value="140">Please Select a Coffee</option>';
        var dates = '';
       for(i in this.selections)
        {

            if(i!='Seasonal') html +='<optgroup label="'+i+'">';
            for(j in this.selections[i])
            {
                if(i!='Seasonal')
                {
                    if($this.size == '2.0 oz' && this.selections[i][j].sku.match(/FRAC/)!=null) html+='<option value="'+this.selections[i][j].id+'">'+this.selections[i][j].name+'</option>';
                    else if($this.size == '8.0 oz' && this.selections[i][j].sku.match(/FRAC/)==null) html+='<option value="'+this.selections[i][j].id+'">'+this.selections[i][j].name+'</option>';
                }


                if((this.selections[i][j].id == this.productId) || (this.selections[i][j].sku == this.productId)){
                    dates = '<b>' + this.selections[i][j].startDate +'</b> to <b>'+this.selections[i][j].endDate+'</b>';
                }
            }
            html+='</optgroup>';
        }
        html+='</select></li>';
        html = '<p>This coffee will only be available from '+dates+'. Please select an alternative coffee to replace this selection in your home delivery schedule when its production ends (you can login to your account to change your selection at any time). If you do not make a selection, your alternate will be Boca Sunrise.</p><ul class="fi"><li class="pt1"><select name="altOptions" id="altOptions">' + html;
        html+='<li class="pt1"><a href="#" id="altOptionsSubmit" class="gbtn sm" style="color:#fff;"><span><span>select</span></span></a></li></ul>';

        $("#bj_dialog").html(html);
        $("#bj_dialog").dialog('option','title','Select an alternative for your seasonal coffee');
        $("#bj_dialog").dialog('open');

        this.addOmnitip();
        this.setChange();
    }

    this.clearAlternate = function(){
        if($(this.select).parents('tr').next().attr('class') == 'altName') $(this.select).parents('tr').next().remove();
    }


    this.setChange = function()
    {
        var $this = this;
        $("#bj_dialog").dialog('option','close',function(){
                 if($($this.select).prev().val()==140)
                {
                    $this.clearAlternate();
                    $($this.select).parents('tr').after('<tr class="altName"><td></td><td colspan=3><div class="notify size2">Alternate Selection: <b>Boca Sunrise Coffee - 8oz</b></div></td></tr>');
                }
                $("#bj_dialog :input").addClass('disabled');
                runValidate();
                $("#bj_dialog .loading").show();
                $("#bj_dialog #dialogContainer").remove();
        })
        


        $("#altOptionsSubmit").unbind().click(function(){
            var options = $("#altOptions");
            var selection = $(options).val();
            var option = $("option[value='"+selection+"']");
            var text = option.text();
            $this.form.find('input').each(function(){
                var thisname = $(this).attr('name');
                //debug(thisname + ":"+ $($this.select).prev().attr('name'));
                if(thisname!=undefined && thisname.match(/altSelection/))
                {
                    if($this.select==null) $(options).val(selection);
                    else
                        {
                         var name = $($this.select).prev().attr('name');
                         if(name==thisname) {
                             $(options).val(selection);
                             $($this.select).prev().val(selection);
                             $this.clearAlternate();
                             //debug($this.select);
                             $($this.select).parents('tr').after('<tr class="altName"><td></td><td colspan=3><div class="notify size2">Alternate Selection: <b>'+text+'</b></div></td></tr>');
                         }
                        }
                }
                else
                {
                    $this.form.append('<input type="hidden" class="hidden" name="altSelection" id="altSelection" value="'+selection+'" />');
                    $this.form.append('<input type="hidden" class="hidden" name="add_to_club_detail" id="add_to_club_detail" value="add to club" />');
                }
            });
            if(selection!="" && $this.select==null && $this.type!='sli'){
                var formId = $this.form.attr('name');
                document.forms[formId].submit();
            }
            else
                {
                    $this.api.close();
                    if($this.type=='sli'){
                        $this.omnitipSubmit();
                    }
                }
        });
    }

    this.addOmnitip = function()
    {

        var d = getDomain();
        var url = d+'/clubProductDetailsAjaxAction.do';
        var $this = this;

         var p = {};

                if($this.descriptions==null)
                    {
                 $.ajax({
                       url: url,
                       data:p,
                       dataType: 'jsonp',
                     //  processData: false,
                       success: function (data, textStatus) {
                               $this.descriptions = data;

                        },
                                        error: function(XMLHttpRequest, textStatus, errorThrown){
                        //   ot.responseError(XMLHttpRequest, textStatus, errorThrown)
                        },
                                        beforeSend: function (XMLHttpRequest) {
                          // $($this.form).parents('div.omnitip').append('<div class="omnitip_loading"><div class="omnitip_loader"><img src="/resources/images/ajax-loader.gif" alt="loading" /></div><div class="omnitip_transparency"></div></div>');
                        },
                                        complete: function (XMLHttpRequest) {
                           // $($this.form).parents('div.omnitip').find('.omnitip_loading').fadeOut(800,function(){$(this).remove();})
                        }
                    });
                    }


var altdata = '';

     

      $('#altOptions').bt({
                            fill: '#ffffff',
                              strokeStyle: '#666666',
                              shadow: true,
                            shadowOffsetX: 1,
                            shadowOffsetY: 1,
                            shadowBlur: 3,
                            shadowColor: 'rgba(0,0,0,.9)',
                            shadowOverlap: false,
                            noShadowOpts: {strokeStyle: '#B7B7B7', strokeWidth: 2},
                            positions: ['right'],
                              spikeLength: 10,
                              spikeGirth: 10,
                              padding: 8,
                              cornerRadius: 2,
                              cssStyles: {
                                fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif',
                                fontSize: '11px'},
                              trigger: 'none',
                              preShow: function(box){
                                

                              },
                              contentSelector: function(){

                                  return altdata;
                              },
                              showTip:function(box){
                                
                                $(box).show();
                                
                                
                              },
                               hideTip: function(box, callback) {
                                $(box).hide();

                        },
                              width: 350
});


     $('#altOptions option').mouseover(function(){
                                    var current = $(this).attr('value');
                                    altdata = $this.parseTipData(current);
                                    if(altdata!='') $("#altOptions").btOn();
                                }).mouseout(function(){
                                    $("#altOptions").btOff();
                                })

      
    }

    this.parseTipData = function(current)
    {
        var html = '';
        var selected = $("#altOptions").val();
        if(current!=null) selected = current;
        $.each(this.descriptions.items, function(i,item){

            if(item.id == selected)
            {
                html+='<div class="omnitip_img"><img src="'+item.thumbnail+'" border="0"></div><div class="omnitip_text"><h4>'+item.name+'</h4><p>'+item.description+'</p>';

            }
        });

        return html;
    }
/*
    this.omnitipSubmit = function()
    {
        var $this = this;
        var p = {};

        p['action'] = 'addToClub';

        $($this.form).find(":input").each(function(){
                var id = $(this).attr('name');
                var val = $(this).val();

                p[id] = val;

        });

            var d = getDomain();
            var url= d+"/addToCartAjax.do";

         $.ajax({
           url: url,
           data:p,
           dataType: 'jsonp',
         //  processData: false,
           success: function (data, textStatus) {
                       $.each(data.items, function(i,item){
                        if(item.success == 'true')
                         {
                            var message = item.message;
                            if(message == '' || message==null) message = '<div class="success">This item has been added to your <a href="'+d+'/viewCart.do">cart</a>!</div>';
                            $($this.form).parents('div.omnitip').find('.omnitip_body_inner').html(message);

                            loadCartModal({
                                    url:'/'
                            });
                        }
                 });
            },
                            error: function(XMLHttpRequest, textStatus, errorThrown){
            //   ot.responseError(XMLHttpRequest, textStatus, errorThrown)
            },
                            beforeSend: function (XMLHttpRequest) {
               $($this.form).parents('div.omnitip').append('<div class="omnitip_loading"><div class="omnitip_loader"><img src="/resources/images/ajax-loader.gif" alt="loading" /></div><div class="omnitip_transparency"></div></div>');
            },
                            complete: function (XMLHttpRequest) {
                $($this.form).parents('div.omnitip').find('.omnitip_loading').fadeOut(800,function(){$(this).remove();})
            }
                                             });
    }
*/
}

