/**
 * hediard.js
 *
 * @author          Alexandru Margineanu (alex.margineanu@redboxdigital.com)
 * @copyright   Redbox Digital
 */

document.observe("dom:loaded", function() {
	hediard.init();
});

var hediard = function() {

        var stepId = null;

	return {		
		init: init,
		initShipping: initShipping,
		hide: function(e) {
			if($(e)) $(e).style.display = 'none';
		},
		bringBack: function(e) {
			if($(e)) $(e).style.left = 0;
		},
                move: function(e) {
			if($(e)) $(e).style.left = '-99999px';
		},
		bindThumbnails: function() {			
			$$(".more-views img").each(this.zoom);
		},
		switchLanguage: switchLanguage,
		switchShipping: switchShipping,
		updateShipping: updateShipping,
		displayAddToCartButton: displayAddToCartButton,
		displayDropdownCart: displayDropdownCart,
		getBrowserLang: getBrowserLang,
                expandFaq: expandFaq,
		zoom: zoom,
                opcProgress: opcProgress,
                delayEasyBanner: delayEasyBanner,
                loyaltyCardRequest: function() {
                    if($('loyalty_card').value=='Request') {
                        $('loyalty_card').value='';
                    } else {
                        $('loyalty_card').value='Request';
                    }
                },
                navMenu: function(){
                      jQuery('ul.sf-menu').sooperfish({
                            multiColumn  : false,
                            hoverClass: 'sfHover',
                            animationShow: {height:'show'},
                            speedShow: 400,
                            easingShow: 'easeOutExpo',
                            delayHide: 0,
                            easingHide: 'easeInSine',
                            animationHide: {height:'hide'},
                            speedHide: 0,
                            autoArrows: false
                  });
                }
	};



	/**
	* When EasyBanner loads you can see the scrollbars,
         * if we delay displaying it for 1 s, the scrollbars
         * are gone
	*/
        function delayEasyBanner() {
                hediard.bringBack.delay(1, 'hero-home');
                window.setTimeout(function() {
                    $('hero-home').fade({duration: 2, from: 0, to: 1});
                }, 800);


        }
        

        /**
	* Developer Utils
         * populate checkout form
         * 
	*/
        function populateCheckoutForm() {
            $('firstname').setValue('Alex');
            $('lastname').setValue('Margi');
            $('email_address').setValue('alex.margineanu@gmail.com');
            $('password').setValue('verdele');
            $('confirmation').setValue('verdele');
        }



	function init(){
                this.navMenu();
		this.bindThumbnails();
		this.getBrowserLang();
		this.displayDropdownCart();
                if($('debug'))  {
                    new Draggable('debug', {});
                }
	}





	/**
	* Detects the browser default
	* language settings
	*/
	function getBrowserLang(){
		var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;
		//console.log("The language is: " + userLang);
	}


	/**
	* Zoom the image by changing its source
	* with the large version
	*/
	function zoom(element){					
		var path = $(element).readAttribute('rel');
		element.observe("click",function() {
			$("image").setAttribute("src", path);
		});
	}




	/**
	* Show available languages when
	* user clicks on 'Change language' link
	*/
	function switchLanguage(){
		isVisible = $('switch').getStyle('left');
		if(isVisible == '-99999px'){
			$('switch').style.left = '-3px';
			$('switch').fade({duration: 0, from: 0.1, to: 1});
			$('switcher').fade({duration: 0, from: 1, to: 0});
		} else {
			hediard.move('switch');
		}
	}



	/**
	* Show available shipping countries popup
	*/
	function switchShipping(){		
		isVisible = $('shipping-popup').getStyle('left');
		if(isVisible == '-99999px'){
			new Effect.Appear($('j2t-overlay'), {duration: 0.5,  to: 0.8});	
			$('shipping-popup').style.left = '-480px';
			$('shipping-popup').fade({duration: 0, from: 0.1, to: 1});
		} else {			
			this.hide('j2t-overlay');
			this.move('shipping-popup');
		}
	}


	/**
	* Updates shipping flag with current 
	* country and stores it in a cookie
	*/
       function updateShipping(country) {
               path = $('shipping-popup').readAttribute('rel');
               img = path + country+'.png'
               $('shippingFlag').setAttribute('src', img);
               setCookie('shippingPreference', country, 365);
               this.move('shipping-popup');
       }




	/**
	* Get saved shipping country
	* from cookie and sets the flag image
	*/
        function initShipping() {
		var country = Mage.Cookies.get('shippingPreference');
		if(!country || country.length == 0 || country == null) {
				country = 'fr';
		}
		this.updateShipping(country);
		
		//hides the popup when user clicks outside
		$$('body').invoke('observe', 'click', function(event) {
			if(Event.element(event).id != 'shippingLabel' && Event.element(event).id != 'shippingFlag' && Event.element(event).id != 'shipping-popup') {
				hediard.move('shipping-popup');
				hediard.hide('j2t-overlay');
			}
		});
		if ($('j2t-overlay')){
			Event.observe($('j2t-overlay'), 'click', this.hide('j2t-overlay'));
		}
        }


      /**
	* Show/hide dropdown cart on hover
	*/
	function displayDropdownCart() {
                $$('.top-cart').each(function(menuItem) {
                      menuItem.hover(
                        function() {
                               //console.log('show menu');
				if($('cart-sidebar')) {
					$('drop-down-cart-header').style.left='-100px';
				}
                        },
                        function() {
                            //console.log('hiding');
                            hediard.move('drop-down-cart-header');
                        },
                        {
                           enterDelay: 0,
                           leaveDelay: 1000
                        }
                      );
                    });

                    overCart = $('drop-down-cart-header');
                    if (overCart) {
                        overCart.hover(
                            function() {
                                    overCart.style.left='-100px';
                            },
                            function() {
                                hediard.move(overCart);
                            },
                            {
                               enterDelay: 100,
                               leaveDelay: 500
                            }
                          );                        
                    }
	}



	/**
	* When the user hovers on a product
	* the add to cart button is showed/hided
	*/
	function displayAddToCartButton() {
                $$('.previewcart').each(function(menuItem) {
                      menuItem.hover(
                        function() {
                                var cid = 'cid-' + $(menuItem).readAttribute('rel');
								if($(cid)) {
									$(cid).style.left=0;
								}
                        },
                        function() {
                            var cid = 'cid-' + $(menuItem).readAttribute('rel');
                            hediard.move(cid);
                        }
                      );
                    });
	}



	/**
	* Expands answer when user clicks
	* on a question or a category
	*/
	function expandFaq(id) {
                var state = $(id).getStyle('display');
		if(state == 'none') {
                    $(id).style.display = 'block';
                } else {
                    $(id).style.display = 'none';
                }
	}



        /**
        * Onepage Checkout - Progress
        * current step - active
        * previous steps - complete
        * future stepts - empty
        */
        function opcProgress(section) {           
          if(section == 'review') {
                $$('#theprogress dt').invoke('removeClassName', 'progress-active').invoke('addClassName', 'complete');
                $('progress-opc-review').addClassName('progress-active');
            } else {
                    stepId = 'progress-opc-' + section;
                    if($(stepId)) {
                        $(stepId).addClassName('progress-active');
                        var _oldSteps = $(stepId).previousSiblings();
                        var _newSteps = $(stepId).nextSiblings();
                        $(_oldSteps).invoke('removeClassName', 'progress-active').invoke('addClassName', 'complete');
                        $(_newSteps).invoke('removeClassName', 'progress-active').invoke('removeClassName', 'complete');
                        $('progress-opc-review').removeClassName('progress-active').removeClassName('complete');
                    }
                    if($('progress-opc-login')) {
                        $('progress-opc-login').addClassName('complete');
                    } 
            }
        }



	/**
	* Util functions
	*/
       function setCookie(c_name, value, expiredays) {
           var exdate = new Date();
           exdate.setDate(exdate.getDate()+expiredays);
           document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toUTCString());
       }

}();
