
/*function jsGet(type){
  if(location.href.match(type)){
    return location.href.split(type+'=')[1].split('&')[0];
  }
}*/

var informationTextTimer;
var informationTextTimerArray = new Array();
var addToCartTimer;
var changeBannerTimer;
var oldBanner;
var AJAX_ERROR = 'ajax_error';
var productPageLeftScroll;

var Site = {

	start: function(){

    /* Cache images */ // $('bannerImage').getProperty('src')]
    new Asset.images(['images/bandeau-rouge.gif', 'images/bandeau-blanc.gif']);

    /* Submit search text */
    //if($('quick_find_header')) $('SearchButton').addEvent('click', function() { alert($('quick_find_header')); });

    /* Index Page */
    //if($('indexDefault')) Lightbox.init();

    /* Hover categories */
    $$('.categories').addEvent('mouseover', function(e) {
      e = new Event(e).stop();

      var banner = this.getProperty('banner');
      if(banner != null) {
        var bannerImage = $('bannerImage');
        // Kill timer
        $clear(changeBannerTimer);
        // backup old banner
        if(typeof(oldBanner) == "undefined") {
          oldBanner = bannerImage.getProperty('src');
        }
        // changer banner
        bannerImage.setProperty('src', banner);
      }
    });

    $$('.categories').addEvent('mouseout', function(e) {
      e = new Event(e).stop();

      if(typeof(oldBanner) != "undefined") {
        // changer banner
        changeBannerTimer = (function(){ $('bannerImage').setProperty('src', oldBanner); }).delay(500);
      }
    });

    if($('CMSPageLeft')) {
      // if var (GET) open_id exists, open asked cms page
      //var cms_id = jsGet('cms_id');
      if(cms_id) {
        Site.showCMSPage(cms_id);
        // Grey selected page
        $$('.cmsname').each (
          function(el) {
            if(el.getProperty('page_id') == cms_id) {
              el.addClass('grey');
            }
          }
        )
      }
    }

    /* Sub-Categories Accordion */
		if ($('accordion')) {
      // if property show_id exists (opening accordion from index page)
      var show_id =  $('accordion').getProperty('show_id');
	 
      Site.Accordion(parseInt(show_id));

      (function(){  // Fix for IE. If not delayed accordion will not open.
        var product_id = open_id;
        if(product_id) {
          // Detect product type base on page asked (main_page)
          var product_type = '';
          //switch(jsGet('main_page')) {
          switch(main_page) {
            case 'featured_products':
              product_type = 'featured';
              break;
            case 'specials':
              product_type = 'specials';
              break;
            default:
              product_type = '';
          }
          // ---
          // Grey selected product
          $$('#accordion .products').each (
            function(el) {
              if(el.getProperty('product_id') == product_id) {
                el.addClass('grey');
              }
            }
          )
          // Show Product
          Site.showProduct(product_id, product_type);
        }
        // ---
    		/* Ajax Request when clicking on Products */
    		$$('#accordion .products').addEvent('click', function(e) {
          e = new Event(e).stop();

          // Grey selected product
          $$('#accordion .products').removeClass('grey');
          this.addClass('grey');

          Site.clickProduct(this);
        });
      }).delay(600); // Fix for IE. If not delayed accordion will not open.
	  
    }

    /* I : Home Page Information Button */
    $$('[class=mainpage_infoicon]').addEvent('click', function(e) {
      e = new Event(e).stop();

      Site.ToggleMainPageInfoDiv(this);
    });

    /* Ajax Request when clicking on CMS Page */
		$$('#CMSPageLeft .cmsname').addEvent('click', function(e) {
      e = new Event(e).stop();

      // Grey selected page
      $$('.cmsname').removeClass('grey');
      this.addClass('grey');

      Site.clickCMS(this);
    });
    
    if($('accordionWrapper')) {
      productPageLeftScroll = new Scroller('accordionWrapper', {area: 200, velocity: 0.08});
      $('accordionWrapper').addEvent('mouseover', productPageLeftScroll.start.bind(productPageLeftScroll));
      $('accordionWrapper').addEvent('mouseout', productPageLeftScroll.stop.bind(productPageLeftScroll));
    }
	},

	/* Toggle product information div */
	ToggleProductInfoDiv: function() {
    var Informationtext = $('Informationtext');
    var visbility = $('Informationtext').getStyle('visibility');
    if(visbility == 'hidden') {
      $clear(informationTextTimer);
      this.setElementStyle('Informationtext', 'visibility', 'visible');
      /*informationTextTimer = (function(){ Site.setElementStyle('Informationtext', 'visibility', 'hidden'); }).delay(3000);*/
    } else
      this.setElementStyle('Informationtext', 'visibility', 'hidden');
	},

	/* Toggle product information div on main page */
	ToggleMainPageInfoDiv: function(element) {
    link_id = (element.getProperty('link_id'));
    $$('[class=Informationtext]').each (
      function(el) {
        if(el.getProperty('link_id') == link_id) {
          if(el.getStyle('visibility') == 'hidden') {
            $clear(informationTextTimerArray[link_id]);
            Site.setElementStyle(el, 'visibility', 'visible');
            informationTextTimerArray[link_id] = (function(){ Site.setElementStyle(el, 'visibility', 'hidden'); }).delay(3000);
          } else {
            Site.setElementStyle(el, 'visibility', 'hidden');
          }
        }
      }
    )
	},

	/* Set element style */
	setElementStyle: function(element_id, element_style, element_value) {
    $(element_id).setStyle(element_style, element_value);
	},

	/* MooPrompt */
  Prompt: function(msgtitle, msgtext) {
    var boxA = new MooPrompt(msgtitle, msgtext, {
      buttons: 0,
      width: 250,
      delay: 2500
		});
  },

  /* Sub-Categories Accordion */  
  Accordion: function(show_id) {
	
	 if(window.ie7){
		var products_accordion = new Accordion('h3.atStart', 'div.atStart', {
		  opacity: false,
		  duration: 300,
		  display: 0, 
		  show: show_id,
		  alwaysHide: true
		},$('accordion'));
	}else{
		var products_accordion = new Accordion('h3.atStart', 'div.atStart', {
		  opacity: false,
		  duration: 300,
		  display: 0, 
		  show: show_id
		  /*alwaysHide: true*/
		 }, $('accordion'));
	 }	
	products_accordion.display(show_id);
  },

  /* Ajax Request when clicking on Add to Cart or Enter in Quantity Box */
  CreateFunction_AddToCart: function() {
    $$('.addToCart').addEvent('click', function(e) {
      e = new Event(e).stop();

      Site.clickAddToCart(this);
    });

    if($('bottleNumber')) {
      $('bottleNumber').addEvent('keypress', function(e) {
        if(e.keyCode == 13) {
          e = new Event(e).stop();

          Site.clickAddToCart(this);
        }
      });
    }
  },

  /* Ajax Request when clicking on Add To Cart */
  clickAddToCart: function(product) {
    var bottleNumber = $('bottleNumber');
    var ID = product.getProperty('product_id');
    var quantity = bottleNumber.value;
    var url = "ajax.php?info=addtocart&id=" + ID + '&quantity=' + quantity;
    var informationTextDiv = $('informationTextDiv');

		bottleNumber.value = '';

		request = new Ajax(url, {
			method: 'get',
			update: null,
			onSuccess: (function(request) {
                    if(request.indexOf(AJAX_ERROR) == -1) {
                      $clear(addToCartTimer);
                      informationTextDiv.addClass('highlight');
                      // set new products number
                      $('productNumber').setText(request);
                      // delay class removing
                      addToCartTimer = (function(){ informationTextDiv.removeClass('highlight'); }).delay(2500);
                    } else {
                      // error
                      error_title = request.substring(request.indexOf(':') + 1, request.indexOf(';'));
                      error_msg = request.substr(request.indexOf(';') + 1, (request.length - request.indexOf(';') + 1));
                      Site.Prompt(error_title, error_msg);
                      delete error_title;
                      delete error_msg;
                    } })
		}).request();
  },

  /* Ajax Request when clicking on Products */
  clickProduct: function(product) {
    var ID =  product.getProperty('product_id');
    var product_type = product.getProperty('product_type');

    Site.showProduct(ID, product_type);
  },

  /* Ajax Request when clicking on CMS Page */
  clickCMS: function(cms_link) {
    var ID =  cms_link.getProperty('page_id');

    Site.showCMSPage(ID);
  },

  /* Show product image */
  showProductImage: function(product_id) {
    var url = "ajax.php?info=product_image&id=" + product_id;
    var image = $('image');
    // Show spinner
    image.empty().addClass('ajax-loading');
    // Hide accordion
    $('accordion').setStyle('display', 'none');
    // Show product image
    $('imgpopup').setStyle('display', 'block');
    // Get product image
    new Ajax(url, {
			method: 'get',
			update: null,
			onSuccess: (function(request) {
                    /* Change classe to hide spinner */
                    image.removeClass('ajax-loading');

                    if(request.indexOf(AJAX_ERROR) == -1) {
                      // show product image
                      image.setHTML(request);
                    } else {
                      // error
                      // Hide product image
                      $('imgpopup').setStyle('display', 'none');
                      // Show accordion
                      $('accordion').setStyle('display', 'block');
                      error_title = request.substring(request.indexOf(':') + 1, request.indexOf(';'));
                      error_msg = request.substr(request.indexOf(';') + 1, (request.length - request.indexOf(';') + 1));
                      Site.Prompt(error_title, error_msg);
                      delete error_title;
                      delete error_msg;
                    } }),
      onError: function() {
        /* Change classe to hide spinner */
        image.removeClass('ajax-loading');
        // Hide product image
        $('imgpopup').setStyle('display', 'none');
        // Show accordion
        $('accordion').setStyle('display', 'block');
			},
			onCancel: function() {
        /* Change classe to hide spinner */
        image.removeClass('ajax-loading');
        // Hide product image
        $('imgpopup').setStyle('display', 'none');
        // Show accordion
        $('accordion').setStyle('display', 'block');
			}
		}).request();
  },

  /* Hide product image */
  hideProductImage: function() {
    // Clear DIV
    $('image').empty();
    // Hide accordion
    $('imgpopup').setStyle('display', 'none');
    // Show product image
    $('accordion').setStyle('display', 'block');
  },

  /* Ajax Request when clicking on CMS Page */
  showCMSPage: function(ID) {
    var url = "ajax.php?info=cmspage&id=" + ID;
		var cmsContentDiv = $('CMSPageRight');

		cmsContentDiv.empty().addClass('ajax-loading');

		new Ajax(url, {
			method: 'get',
			update: null,
			onSuccess: (function(request) {
                    /* Change classe to hide spinner */
                    cmsContentDiv.removeClass('ajax-loading');

                    if(request.indexOf(AJAX_ERROR) == -1) {
                      // show product info
                      cmsContentDiv.setHTML(request);
                    } else {
                      // error
                      error_title = request.substring(request.indexOf(':') + 1, request.indexOf(';'));
                      error_msg = request.substr(request.indexOf(';') + 1, (request.length - request.indexOf(';') + 1));
                      Site.Prompt(error_title, error_msg);
                      delete error_title;
                      delete error_msg;
                    } }),
      onError: function() {
        /* Change classe to hide spinner */
        cmsContentDiv.removeClass('ajax-loading');
			},
			onCancel: function() {
        /* Change classe to hide spinner */
        cmsContentDiv.removeClass('ajax-loading');
			}
		}).request();
  },

  /* Ajax Request when clicking on Products */
  showProduct: function(ID, product_type) {
		var url = "ajax.php?info=product&id=" + ID + "&product_type=" + product_type;
		var productDiv = $('productPageRight');

		productDiv.empty().addClass('ajax-loading');

		new Ajax(url, {
			method: 'get',
			update: null,
			onSuccess: (function(request) {
                    /* Change classe to hide spinner */
                    productDiv.removeClass('ajax-loading');

                    if(request.indexOf(AJAX_ERROR) == -1) {
                      // show product info
                      productDiv.setHTML(request);

                      /* Initialize mootabs */                               /* 221px */
                      if($('productTabs')) new mootabs('productTabs', {height: '234px', width: '399px', changeTransition: 'none', mouseOverClass: 'over'});
                      /* Parse product info for images */
                      //if($('productTop')) Lightbox.init();
                      /* Show image on top of accordion */
                      if ($$('.image_popup')) {
                        $$('.image_popup').addEvent('click', function(e) {
                          e = new Event(e).stop();

                          Site.showProductImage(ID);
                        });

                        /* Hide image */
                        if ($('imgpopup')) {
                          $('close').addEvent('click', function(e) {
                            e = new Event(e).stop();

                            Site.hideProductImage();
                          });
                        }
                      }
                      /* I : Product Information Button */
                  		if ($('infoicon')) {
                        $('infoicon').addEvent('click', function(e) {
                          e = new Event(e).stop();

                          Site.ToggleProductInfoDiv();
                        });
                  		}
                      /* Add Event for Add To Cart requests */
                      if($('productTop') || $('productTitle')) Site.CreateFunction_AddToCart();
                    } else {
                      // error
                      error_title = request.substring(request.indexOf(':') + 1, request.indexOf(';'));
                      error_msg = request.substr(request.indexOf(';') + 1, (request.length - request.indexOf(';') + 1));
                      Site.Prompt(error_title, error_msg);
                      delete error_title;
                      delete error_msg;
                    } }),
      onError: function() {
        /* Change classe to hide spinner */
        productDiv.removeClass('ajax-loading');
			},
			onCancel: function() {
        /* Change classe to hide spinner */
        productDiv.removeClass('ajax-loading');
			}
		}).request();
  }
};

window.addEvent('load', Site.start);
