
(function ($) {
  var languages_timeout = 300;
	var languages_closetimer		= null;


	/* share this published id */
	if(typeof stLight !== 'undefined') {
		stLight.options({publisher:'3262c9b8-c625-4286-b7c4-f4d80284b832', onhover: false});
	}
	
	Drupal.behaviors.myModuleBehavior = {
			attach: function (context, settings) {


				// Clear default text on focus, and put it back on blur. Also displays Popup.
				$('.view-subscribe-to-newsletter input.form-text', context)
				.bind('click focus', function(e){				   
				  this.value = '';
				}
				);
	  
				// dismiss #top_offpage-wrapper when clicked
				// additionally grey out screen
				$('#top_offpage-wrapper').click(function(event) {
						$(this)
							.animate(
								{ top: "-290px" }, {
								duration: 'fast',
								easing: 'easeOutQuart'
							});
						$('#screen').css(
							{ display: "block",
							  opacity: 0.7,
							  width: $(document).width(),
							  height: $(document).height()
							});
							
						$('#screen')
							.animate(
								{ opacity: 0.0}, {
								duration: 'fast',
								complete: function() {
									$('#screen').css({
										display: "hidden",
										"z-index": -10000
									});
								}
							});
				});
				
				// show #top_offpage-wrapper when #header_customer_zone_link clicked
				// additionally 'un'grey out screen
				$('.customer_zone_link').click(function(event) {
						$('#top_offpage-wrapper')
							.animate(
								{ top: "0px" }, {
								duration: 400,
								easing: 'easeOutBounce'
							});
						$('#screen').css(
							{ display: "block",
							  opacity: 0,
							  "z-index": 91,
							  width: $(document).width(),
							  height: $(document).height()
							});

						$('#screen')
							.animate(
								{opacity: 0.7}, {
								duration: 'fast'
							});
				});
				
				
				// show and hide languages
				$('#header_language').bind('mouseover', languages_show);
				$('#header_language').bind('mouseout', languages_timer);
				$('#block-locale-language').bind('mouseover', languages_show);
				$('#block-locale-language').bind('mouseout', languages_timer);

		 
				// anchor_list for tab_content_view
				$('.view-anchor-list .views-row').click(function(event) {
					// calculate anchor position
					count = 0;
					current = event.currentTarget;
					while(current.previousElementSibling) {
						current = current.previousElementSibling;
						count++;
					}
					
					// simulate tab click trigger
					$('#views_slideshow_pager_field_item_top_tab_content_view-block_' + count).triggerHandler('click');
					$('#views_slideshow_pager_field_item_top_tab_content_view-default_' + count).triggerHandler('click');					
					items = $('.view-tab-content-view');
					if(items) {
						ScrollToElement(items[0]);
					}
				})
				
				
				
				// make all polaroids same size when images get loaded
				$('.ds-pseudo_polaroid').waitForImages(function() {
					MakePseudoPolaroidsTheSameHeight();
				});

		
				// make all flexible items in a row same height when images get loaded
				$('.pane-flexible-item-list').waitForImages(function() {
  				SetCorrectFlexibleItemHeight();
				});
			}
	};
	
  function languages_timer(){
		languages_canceltimer();
		languages_closetimer = window.setTimeout(languages_close, languages_timeout);
	}

	function languages_canceltimer(){
		if (languages_closetimer) {
			window.clearTimeout(languages_closetimer);
			languages_closetimer = null;
		}
	}

	function languages_close(){
    $('#block-locale-language').hide();
	}

	function languages_show(){
    languages_canceltimer();
  	$('#block-locale-language').css(
		{
			'left': $('#header_language')[0].offsetLeft + 300 + $('#header_top')[0].offsetLeft - 5,
			'top': $('#header_language')[0].offsetTop + $('#header_language')[0].offsetHeight + 26
		});
		$('#block-locale-language').show();
  }

  function SetCorrectFlexibleItemHeight() {

    var current_item_list = Array();
    var current_width = 0;
    var items = $('.node-flexible-item.view-mode-full');
    var current_item_index = 0;
    while(current_item_index < items.length) {
      current_item = items.slice(current_item_index, current_item_index+1);
      var current_item_width = 0;
      if(current_item.hasClass('normal-width')) {
        current_item_width = 1;
      } else if(current_item.hasClass('double-width')) {
        current_item_width = 2;
      } else if(current_item.hasClass('triple-width')) {
        current_item_width = 3;
      }

      if((current_width + current_item_width) > 3) { /* it doesn't fit */
        MakeSameHeight(current_item_list);
        current_item_list = Array();
        current_width = 0;
      }

      current_item_list.push(current_item);
      current_width = current_width + current_item_width;
      current_item_index++;
    }

    if(current_item_list.length > 0) {
        MakeSameHeight(current_item_list);
        current_item_list = Array();
        current_width = 0;
    }
  }

  function MakeSameHeight(items) {  
		var height = 0;
    for(var ii=0; ii<items.length; ii++) {
      if(height < items[ii].height())
        height = items[ii].height();
    } 

    for(var ii=0; ii<items.length; ii++) {
      items[ii].height(height);
    }
  } 

  function MakePseudoPolaroidsTheSameHeight() {
		height = 0;
		$('.ds-pseudo_polaroid').each(function(index) {
			if(height < $(this).height())
				height = $(this).height();
		});

		$('.ds-pseudo_polaroid').each(function(index) {
			// set new height correcting effect of border and padding
			$(this).height(height);
		});
	}

	function GetAbsolutePosition(theElement) {
		var posX = 0;
		var posY = 0;
				  
		while(theElement != null){
			posX += theElement.offsetLeft;
			posY += theElement.offsetTop;
			theElement = theElement.offsetParent;
		}
										  
		return [posX, posY];
	}	

	function ScrollToElement(theElement) {
		pos = GetAbsolutePosition(theElement);
						  
		window.scrollTo(pos[0], pos[1]);
	}	
  
})(jQuery);
;
/*
 * waitForImages 1.3.2
 * -----------------
 * Provides a callback when all images have loaded in your given selector.
 * http://www.alexanderdickson.com/
 *
 *
 * Copyright (c) 2011 Alex Dickson
 * Licensed under the MIT licenses.
 * See website for more info.
 *
 */

;(function($) {
    
    // CSS properties which contain references to images. 
    $.waitForImages = {
        hasImageProperties: [
        'backgroundImage',
        'listStyleImage',
        'borderImage',
        'borderCornerImage'
        ]
    };
    
    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
    $.expr[':'].uncached = function(obj) {
        return $(obj).is('img[src!=""]') && ! obj.complete; 
    };
    
    $.fn.waitForImages = function(finishedCallback, eachCallback, waitForAll) {

        // Handle options object.
        if ($.isPlainObject(arguments[0])) {
            eachCallback = finishedCallback.each;
            waitForAll = finishedCallback.waitForAll;
            finishedCallback = finishedCallback.finished;
        }

        // Handle missing callbacks.
        finishedCallback = finishedCallback || $.noop;
        eachCallback = eachCallback || $.noop;

        // Convert waitForAll to Boolean
        waitForAll = !! waitForAll;

        // Ensure callbacks are functions.
        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
            throw new TypeError('An invalid callback was supplied.');
        };

        return this.each(function() {
            // Build a list of all imgs, dependent on what images will be considered.
            var obj = $(this),
                allImgs = [];

            if (waitForAll) {
                // CSS properties which may contain an image.
                var hasImgProperties = $.waitForImages.hasImageProperties || [],
                    matchUrl = /url\((['"]?)(.*?)\1\)/g;
                
                // Get all elements, as any one of them could have a background image.
                obj.find('*').each(function() {
                    var element = $(this);

                    // If an `img` element, add it. But keep iterating in case it has a background image too.
                    if (element.is('img:uncached')) {
                        allImgs.push({
                            src: element.attr('src'),
                            element: element[0]
                        });
                    }

                    $.each(hasImgProperties, function(i, property) {
                        var propertyValue = element.css(property);
                        // If it doesn't contain this property, skip.
                        if ( ! propertyValue) {
                            return true;
                        }

                        // Get all url() of this element.
                        var match;
                        while (match = matchUrl.exec(propertyValue)) {
                            allImgs.push({
                                src: match[2],
                                element: element[0]
                            });
                        };
                    });
                });
            } else {
                // For images only, the task is simpler.
                obj
                 .find('img:uncached')
                 .each(function() {
                    allImgs.push({
                        src: this.src,
                        element: this
                    });
                });
            };

            var allImgsLength = allImgs.length,
                allImgsLoaded = 0;

            // If no images found, don't bother.
            if (allImgsLength == 0) {
                finishedCallback.call(obj[0]);
            };

            $.each(allImgs, function(i, img) {
                
                var image = new Image;
                
                // Handle the image loading and error with the same callback.
                $(image).bind('load error', function(event) {
                    allImgsLoaded++;
                    
                    // If an error occurred with loading the image, set the third argument accordingly.
                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');
                    
                    if (allImgsLoaded == allImgsLength) {
                        finishedCallback.call(obj[0]);
                        return false;
                    };
                    
                });

                image.src = img.src;
            });
        });
    };
})(jQuery);
;

