var feed_data;
var margin_basket = 0; // is the value used for dropping the basket, should be 0 from startup. is set to 1 when opening the basket and reset to 0 when closing
var basket_items = 0; // number of items in basket, can be changed if there are items in the basket
var basket_item_timer,add_item_timer; // place holder for the timer
var animation_duration = 300; // duration of the dropdown
var highlight_duration = 1500; // duration of the highlight
var item_fade_duration = 2000; // duration of the item fading in
var startup_duration = 1500;
var highlight_color = '#ffe400'; // highlight color
var basket_state = 0; // state of the basket(0 = closed, 1 = open)
var prepend_code = ''; // '<div><table cellpadding="0" cellspacing="0" summary="product"><tr><td>added item</td></tr></table></div>';//code that is inserted in the basket. everything between the '<td></td>' can be replaced
var basket_total_price = 0;
var default_basket_height;
var latest_feed;
// dom  element selectors
var basket_container, container_right, basket_container_wrap, basket_close_wrap, basket_close, basket_link, basket_item_count, mini_basket, basket_total_price, basket_extra_info, basket_proceed_text, basket_edit, basket_total, basket_link_a, basket_container_wrap_p_last;
 
// creates script tag and appends it to the header
wep.basket.getBasketJsonData = function(){
	var date = new Date(); 
	wep.feedDomainBasket = (wep.feedDomainBasket.indexOf("?") != -1) ? wep.feedDomainBasket+"&noCache="+date.getTime() : wep.feedDomainBasket+"?noCache="+date.getTime();
    this.head = document.getElementsByTagName("head").item(0);
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", wep.feedDomainBasket );
    this.head.appendChild(this.scriptObj);
    latest_feed = this.scriptObj;
};
 
// inserts JSON data into header
wep.basket.getBasketJsonData();
 
// assigns feed data
wep.basket.basket_json_feed = function(data) {
                feed_data = data;
}
 
// initialize basket on document ready
jQuery(function(){
                if(wep.feedDomainBasket != null && jQuery('div#topbar').hasClass('wepType2')) {
                               setTimeout(function(){shopping_basket.init();},100);
                }
});                           
 
var shopping_basket = {
  init: function(){
 
                basket_container = jQuery('div#cntHeaderRow div#cntBasketContainer');
                container_right = jQuery('div#cntHeaderRow div#cntContainerRight');
                basket_container_wrap = jQuery('div#cntHeaderRow div#cntBasketContainerWrap');
                basket_close_wrap = jQuery('div#cntHeaderRow div#cntBasketCloseWrap');
                basket_close = jQuery('div#cntHeaderRow a#cntBasketClose');
                basket_link = jQuery('div#cntHeaderRow li#cntBasketLink');
                basket_item_count = jQuery('div#cntHeaderRow em.cntBasketItemsCount');
                mini_basket = jQuery('div#cntHeaderRow div#cntBasketContainerWrap div#cntMiniBasket');
                
                basket_total_price = jQuery('div#cntHeaderRow span.cntBasketTotalPrice');
                basket_extra_info = jQuery('div#cntHeaderRow p.cntBasketExtra'); 
                basket_proceed_link = jQuery('div#cntHeaderRow a.cntBasketProceed');
                basket_proceed_text = jQuery('div#cntHeaderRow span.cntBasketProceedText');
                basket_bottom_proceed_link = jQuery('div#cntHeaderRow a.cntProceedBottom');
                basket_bottom_proceed_text = jQuery('div#cntHeaderRow a.cntProceedBottom span.cntBasketProceedText');
                basket_edit = jQuery('div#cntHeaderRow p.cntBasketChange');
                basket_total = jQuery('div#cntHeaderRow span.cntBasketTotalText');
                basket_link_a = basket_link.find('a');
                basket_container_wrap_p_last = basket_container_wrap.find('p:last');
                default_basket_height = 25;
                 
                // set start state of basket
                shopping_basket.basket_onload();
                
                // initialize basket button properties
                shopping_basket.open_basket();
                shopping_basket.close_basket();
                shopping_basket.link_behavior();
 
  },
  // open the basket and show the close button
  open_basket: function(){
    basket_link.live('mouseenter',function(){
      if(basket_items !== 0){
                               if(jQuery('div#wep_expandedContent').css('visibility') == 'visible')
                               {
                                               wep.closePane();
                                               jQuery('div#wep_buttons a.wep_buttonSelected').attr('class','wep_button');
                               }
                                 
        marginBasket = 0;
        basket_link_a.addClass('cntBasketActive');
        shopping_basket.animate_basket(marginBasket,true,false);
      }else{
        basket_link_a.css('text-decoration','underline');
      }
    });
  },
  link_behavior: function(){
                basket_link.live('mouseleave',function(){
      basket_link_a.css('text-decoration','none');
    });
  },
  // close the basket and hide the close button
  close_basket: function(){
                  basket_close.live('click',function(e){
                  e.preventDefault();
      if(basket_items === 0){marginBasket = '-'+(basket_container_wrap.height()+10);}
      else{marginBasket = '-'+(basket_container_wrap.height()-default_basket_height)}
      if(basket_items === 0){basket_link_a.removeClass('cntBasketActive');}
      shopping_basket.animate_basket(marginBasket,false,false);
                  basket_container_wrap.css("padding-bottom",0);
    });  
  },
  
  /* 
    open closes the basket and close button, if an item is added. the 3 params are 
    marginBasket => the height which has to be animated
    basketOpen => if the basket needs to be opened or closed true = open, false = close
    addedItem => if an item is added to the basket
  */
  animate_basket: function(marginBasket,basketOpen,addedItem){
    if(basketOpen){
      // opening the basket
                  basket_container_wrap.parent().addClass('cntBasketOpen');
                  basket_container_wrap.css("padding-bottom",7);
      basket_container.animate({'margin-top':marginBasket},'slow',function(){
                basket_container_wrap_p_last.addClass('cntBasketProceedActive');
        basket_close_wrap.animate({'margin-top':-7},animation_duration,function(){
          basket_state_val = basket_state;
          basket_state = 1;
        });
      });
    }else{
    // closing the basket
                               basket_container_wrap_p_last.removeClass('cntBasketProceedActive');
                               basket_container.animate({'margin-top':marginBasket},'slow',function(){
                                               basket_close_wrap.animate({'margin-top':-27},animation_duration,function(){
                basket_state = 0;
        });
      });
                  basket_container_wrap.parent().removeClass('cntBasketOpen');
    }
  },
  
  // basket startup triggers
  // no items in basket
  basket_onload: function(){
                
                // close the basket when wep buttons hover
                jQuery("div#wep_buttons").find("a").mouseenter(function() {
                                               basket_close.click();
                });
                
                jQuery("input#wep_searchBox").keyup(function() {
                                               
                                               if(jQuery(this).val().length >= 2)
                                               {
                                                               basket_close.click();
                                               }
                });
                
                
                // Check if there are items added to the basket or not
                if(feed_data != null) {
                               
                               // Set language specific element texts
                               shopping_basket.set_basket_texts();
                               basket_container_wrap.show();
                               
                               shopping_basket.prepare_basket();
                                               
                               marginBasket = '-'+(basket_container_wrap.height()-default_basket_height);
                               basket_container_wrap_p_last.removeClass('cntBasketProceedActive');
                               basket_link_a.addClass('cntBasketActive');
                               
                }
                else {
							   basket_link_a.removeAttr('href');
							   basket_link_a.addClass('noLink');
							   
				
                               mini_basket.html('');
                               if(basket_link_a.hasClass('cntBasketActive')){
                                 basket_close_wrap.animate({'margin-top':-27},animation_duration);
                                 basket_link_a.removeClass('cntBasketActive');
                                 basket_item_count.html('0');
                                 basket_items = 0;
                               }
                               marginBasket = '-'+(basket_container_wrap.height()+10);
                }
                
                basket_container.css('margin-top',parseInt(marginBasket));
                                   
  },
    
  // calculates the total amount of added items.
  count_basket_items: function(){
                               var total_items = 0;
                               for(var i = 0; i < feed_data.items.length; i++)    {
                                               total_items += parseInt(feed_data.items[i].quantity);
                               }
                               return total_items;
                },
  
                prepare_basket: function(){
 
                               var total_cost = feed_data.order_total.amount;
                               
                               basket_items = shopping_basket.count_basket_items();
                               added_items_list = shopping_basket.get_added_basket_items();
                                                               
                               mini_basket.html(added_items_list);
                               basket_total_price.html(total_cost);
                               
                               basket_item_count.html('(' + basket_items + ')'); // sets number of items in basket
  
                },
                
                set_basket_texts: function(){
                                var basket_edit_link = basket_edit.find('a');
                               // close button text
                               basket_close.html(feed_data.text_close); 
                               // extra information text
                               basket_extra_info.html(feed_data.text_shipping); 
                               // proceed button text
                               basket_proceed_text.html(feed_data.link_checkout_top.caption);
                               basket_bottom_proceed_text.html(feed_data.link_checkout_bottom.caption);
                               // proceed button url
                               basket_proceed_text.attr('title',feed_data.link_checkout_top.url);
                               basket_proceed_link.attr('href',feed_data.link_checkout_top.url);
                               
                               basket_bottom_proceed_text.attr('title',feed_data.link_checkout_bottom.url);
                               basket_bottom_proceed_link.attr('href',feed_data.link_checkout_bottom.url);
                               // edit basket text
                               basket_edit_link.html(feed_data.link_change.caption);
                               // edit basket title
                               basket_edit_link.attr('title',feed_data.link_change.caption);
                               // edit basket url
                               basket_edit_link.attr("href",feed_data.link_change.url);
                               // total cost text
                               basket_total.html(feed_data.order_total.caption);
  },
  
  // Populates added items.
  get_added_basket_items: function(){
                               var basket_items_list_html = '';
                               for(var i = 0; i < feed_data.items.length; i++) {
                                               var current_item =feed_data.items[i];
                                               basket_items_list_html += '<div><table cellpadding="0" cellspacing="0" summary="product"><tr>';
                                               basket_items_list_html += '<td>'+current_item.quantity+' x '+current_item.description+'</td></tr></table></div>';
                               }
                               return basket_items_list_html;
  },
  
  /* 
  If basket is opened, it only highlights the new item. If it is closed, then it shows the basket,
  highlights the item and finally hides it.
  */
  added_item_highlight: function(basket_state_val, updt){

                shopping_basket.basket_onload();
                  
						   var highlight_item;
						   						   
						   for(var i = 0; i < feed_data.items.length; i++) {
							   var item_index = i;
							   if(feed_data.items[i].id == updt){
									break;
							   }
							   
							   
								
                            }
						   
						   if(updt){
							highlight_item = mini_basket.find('table tr').eq(item_index);
						   }
						   else {
							highlight_item = mini_basket.find('table:last tr');
						   }
				  
						   if(basket_state_val) {
										   highlight_item.effect('highlight',{color:highlight_color},highlight_duration);
						   }
						   else {
										   
										   basket_container.animate({'margin-top':'0'},'slow', function(){
														   highlight_item.effect('highlight',{color:highlight_color},highlight_duration,function(){
																		  margin_basket = '-'+(basket_container_wrap.height()-default_basket_height);
														   basket_container.animate({'margin-top': parseInt(margin_basket)},'slow');
																		  
														   });
														   
										   });
										   
						   }
                               
                               
  
  },
  // Fetches the new feed from the url
  get_update_feed: function(url) {

					var date = new Date();
					this.head = document.getElementsByTagName("head").item(0);
					this.head.removeChild(latest_feed);
					wep.feedDomainBasket = (url.indexOf("?") != -1) ? url+"&noCache="+date.getTime() : url+"?noCache="+date.getTime()
					wep.basket.getBasketJsonData();
  },
  // Synchronizes the basket content with SSS  
  update_basket: function(feed){
				   
					eval(feed);

					wep.basket.basket_json_feed = function(data) {
						feed_data = data;
					}

					shopping_basket.prepare_basket();
					shopping_basket.set_basket_texts();
					basket_container_wrap.show();
					shopping_basket.added_item_highlight(basket_state,feed_data.updated);

  }               
}

