$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
     }  
  }); 

  return this;
};

$(document).ready(function() {
        $('.tile').live('click', function() {
           window.location.href = $(this).find('.tile_link a').attr('href');
        });

	$('.designer').hover(function() {
		$('.designer_link', this).toggleClass('designer_link_hover');
		$('.designer_link a', this).toggleClass('designer_link_hover');
	});
	
	$('#teaser_left').hover(function() {
	    if($("#teaser_left_overlay").css('display') == 'none') {
	        $("#teaser_left_overlay").toggle();
	    }
                var height = $("#teaser_left_overlay").attr('anim_height') ? $("#teaser_left_overlay").attr('anim_height') : '130px';
		$("#teaser_left_overlay").stop(true,false).animate({height: height});
	}, function() {
		$("#teaser_left_overlay").stop(true,false).animate({height: '0px'}, function() {
		    if($("#teaser_left_overlay").height() == 0) {
		        $("#teaser_left_overlay").toggle();
		    }
		});

	});
	$('#teaser_right').hover(function() {
    	if($("#teaser_right_overlay").css('display') == 'none') {
	        $("#teaser_right_overlay").toggle();
	    }
                var height = $("#teaser_right_overlay").attr('anim_height') ? $("#teaser_right_overlay").attr('anim_height') : '130px';
		$("#teaser_right_overlay").stop(true,false).animate({height: height});
	}, function() {
		$("#teaser_right_overlay").stop(true,false).animate({height: '0px'}, function() {
		    if($("#teaser_right_overlay").height() == 0) {
		        $("#teaser_right_overlay").toggle();
		    }
		});

	});
	
	$('.designer').hover(function() {
		$('.designer_link', this).toggleClass('designer_link_hover');
		$('.designer_link a', this).toggleClass('designer_link_hover');
	});
	//$('#lookbook ul').sortable();
	$('#lookbook ul li').live('hover', function() {
    $('.overlay', this).toggleClass('hidden');
  }); 	
  
  $('#scrollRight').mouseout(function(e) {
    $('#scrollRight').data('mousedown', false);
    $('#scrollRight').data('iterations', 0);
  });
  
  $('#scrollLeft').mouseout(function(e) {
    $('#scrollLeft').data('mousedown', false);
    $('#scrollLeft').data('iterations', 0);
  });
  
  $('#scrollRight').mousedown(function(e) {
    $('#scrollRight').data('mousedown', true);
    $('#scrollRight').data('iterations', 0);
    setTimeout(technicalDataScrollRight, 200);
  });
  
  $('#scrollRight').mouseup(function(e) {
    $('#scrollRight').data('mousedown', false);
    if($('#scrollRight').data('iterations') < 5) {
    maxLeft = 715 - $('#technical_data_image').width();
        maxLeft = (maxLeft < 0) ? maxLeft : 0;
        newLeft = $('#technical_data_image').position().left-560;
        newLeft = Math.max(newLeft, maxLeft);
        $('#technical_data_image').animate({left: newLeft+'px'}, function() {
            updateTechnicalDataArrows();
        });
    }
    $('#scrollRight').data('iterations', 0);
  });
  
  $('#scrollLeft').mousedown(function(e) {
    $('#scrollLeft').data('mousedown', true);
    $('#scrollLeft').data('iterations', 0);
    setTimeout(technicalDataScrollLeft, 200);
  });
  
  $('#scrollLeft').mouseup(function(e) {
    $('#scrollLeft').data('mousedown', false);
    if($('#scrollLeft').data('iterations') < 5) {
        newLeft = $('#technical_data_image').position().left+560 < 0 ? $('#technical_data_image').position().left+560 : 0;
        $('#technical_data_image').animate({left: newLeft+'px'}, function(){
            updateTechnicalDataArrows();
        });
    }
    $('#scrollLeft').data('iterations', 0);
  });
  
  
  


  $('#lookbook_infotext').click(function(e) {
      $(this).animate({opacity: 0}, 1000, function() {$(this).detach()});
      return false;
  });
  
  $('.sidebar_link a').not('.simple').click(function() {
      $(this).closest('.sidebar_element').prevAll('.sidebar_element').find('div.sidebar_link a').not('.simple').closest('.sidebar_element').find('div.sidebar_content:visible').toggle('blind');
      $(this).closest('.sidebar_element').nextAll('.sidebar_element').find('div.sidebar_link a').not('.simple').closest('.sidebar_element').find('div.sidebar_content:visible').toggle('blind');
      $(this).closest('.sidebar_element').find('div.sidebar_content').toggle('blind');
      /*
      that = $(this);
      if($('.sidebar_content:visible').length > 0) {
          $('.sidebar_content:visible').each(function() {
          //console.log(that.parent().parent().html == $(this).parent());
              if(that.parent().parent().html() != $(this).parent().html()) {
                  $(this).hide('blind', function() { });
              }
              if(that.parent().parent().html() != $(this).parent().html()) {
                  that.parent().next('div').toggle('blind');
              }
          });
      }
      else {
          $(this).parent().next('div').toggle('blind');
      }
      */
      return false;
      
  });
  
  $('.sidebar_link a.simple').live('click', function() {
      $(this).closest('.sidebar_link').next('div').toggle('blind');
      return false;
  });
  
  //per javascript auf 0 setzen, damit pfeil bei non-js zu sehen ist
  $('#lookbook_infotext_proceed').css('opacity', 0);
  
  $('#lookbook_infotext').hover(function(e) {
      $('#lookbook_infotext_proceed').data('mouseover', 'true');
      $('#lookbook_infotext_proceed').stop().animate({opacity: 1});
      }, function(){
      $('#lookbook_infotext_proceed').stop().animate({opacity: 0}, function() {
          $('#lookbook_infotext_proceed').data('mouseover', 'false');
      });
  });
  setTimeout(showLookbookInfotextProceed, 5000);
  
  $('.assembly_headline').click(function() {
      $(this).parent().prevAll('.assembly_item').find('div.assembly_content:visible').toggle('blind');
      $(this).parent().nextAll('.assembly_item').find('div.assembly_content:visible').toggle('blind');
      $(this).parent().find('div.assembly_content').toggle('blind');
      return false;
  });
  
  $('.press_image_headline').click(function() {
      $(this).parent().prevAll('.press_image_item').find('div.press_image_content:visible').toggle('blind');
      $(this).parent().nextAll('.press_image_item').find('div.press_image_content:visible').toggle('blind');
      $(this).parent().find('div.press_image_content').toggle('blind');
      return false;
  });
  
  $('.merchant_headline').click(function() {
    var that = $(this);
  	$(this).parent().siblings().find('div.merchant_content').each(function(){
	  		  if($(this).css('display') == 'block'){
	  			  $(this).toggle('blind');
	  			  for(var i=0;i<markers.length;i++) {
                        if(markers[i].documentID == $(this).parent().siblings().find('div.merchant_headline').attr('marker')) {
                            markers[i].setIcon(merchantMarkerIcon);
                        }
                    }
	  		  }
	  		  else {
	  		      // click marker
	  		      //console.log($(this).parent().siblings().find('div.merchant_headline').attr('marker'));
	  		      //markers[''+that.attr('marker')].click();
	  		  }
	  });
	  $(this).parent().find('div.merchant_content').toggle('blind');
	  for(var i=0;i<markers.length;i++) {
          if(markers[i].documentID == $(this).attr('marker')) {
              markers[i].setIcon(merchantMarkerIconBlack);
          }
          else {
              markers[i].setIcon(merchantMarkerIcon);
          }
      }
      return false;
  });
  
  $('.brochure_form_item').find('a.remove_link').live('mouseover', function(){
      $('#brochure_form_status').children('span').html($(this).attr('title'));
  });
  
  $('.brochure_form_item').find('a.remove_link').live('mouseout', function(){
      $('#brochure_form_status').children('span').html($('#brochure_form_status').attr('title'));
  });
  
  $('.brochure_form_item').children('div').hover(function(){
      $(this).find('a.remove_link').toggle();}, function() {
      $(this).find('a.remove_link').toggle();
  });
  
  // Formulare der einzelenen Produkte zum bestellen mehrere Brocschueren
  // im Partnerbereich
  $('.brochure_form_partner').submit(function() {
      addBrochurePartner($(this).attr('id'), $(this).find('input[name=brochure_count]').val());
      return false;
  });
  
  $('.brochureFormClose').toggle();
  
  $('.product_color').hover(function(){
        $('.product_colors_detail').toggle().css('background-color', $(this).attr('color'));
    }, function() {
        $('.product_colors_detail').css('display', 'none');
  });
  
  $('.corian_color').hover(function(){
        $('.corian_colors_detail').toggle().css('background-color', $(this).attr('color'));
    }, function() {
        $('.corian_colors_detail').css('display', 'none');
  });
  
  $('.surface').hover(function(){
        $('.surface_detail').toggle();
        $('.surface_detail_image').attr('src', 'project/media/images/surfaces/'+$(this).attr('surface')+'_gross.jpg');
    }, function() {
        $('.surface_detail').css('display', 'none');
  });
  
  $('#contactperson_search_form select').change(function() {
      $(this).closest('form').submit();
  });
  
  initPlaceholders();
  initPlaceholdersTextarea();
});

/**
 * Methode um den aktuellen Standort des Clients zu ermitteln
 */ 
var getClientLocation;
if (google.loader.ClientLocation) {
  getClientLocation = function() {
	  return google.loader.ClientLocation;
  }
} else {
  document.write('<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>');
  getClientLocation = function() {
    return {
      latitude: geoip_latitude(),
      longitude: geoip_longitude(),
      address: {
        city: geoip_city(),
        country: geoip_country_name(),
        country_code: geoip_country_code(),
        region: geoip_region_name()
      }
    };
  }
}

/**
 * Methode um Formularfelder, die einen Standardtext enthalten, bei "onFocus" leer zu machen.
 * Bei "onBlur" wird der Standardtext wieder eingetragen.
 * Der Standardtext muss im Attribut placeholder="" vorhanden sein.
 * Formularfelder kommasepariert der Variablen "placeHoldersSelector" zuweisen.
 */
var initPlaceholders = function() {
    var placeHoldersSelector = '.newsletter_email, #searchString, .suggest_email, .recommendation_email';
    $(placeHoldersSelector).each(function() {
        var str = 'placeholder';
        if(!(str in document.createElement('input'))) {
            var placeholder = $(this).attr(str);
            $(this).addClass(str)
                .val(placeholder)
                .focus(function() {
//                    if($(this).val() == placeholder) {
                        $(this).val('');
                        $(this).removeClass(str);
//                    }
            }).blur(function() {
                if($(this).val() == '') {
                    $(this).addClass(str);
                    $(this).val(placeholder);
                }
            });
        }
    });
}

var initPlaceholdersTextarea = function() {
    var placeHoldersSelector = '.textArea';
    $(placeHoldersSelector).each(function() {
        var str = 'placeholder';
        if(!(str in document.createElement('textarea'))) {
            var placeholder = $(this).attr(str);
            $(this).addClass(str)
                .val(placeholder)
                .focus(function() {
//                    if($(this).val() == placeholder) {
                        $(this).html('');
                        $(this).removeClass(str);
                        $(this).css('color', '#000');
//                    }
            }).blur(function() {
                if($(this).html() == '') {
                    $(this).addClass(str);
                    $(this).html(placeholder);
                    $(this).css('color', '#666');
                }
            });
        }
    });
}

function technicalDataScrollRight(){
    maxLeft = 715 - $('#technical_data_image').width();
    maxLeft = (maxLeft < 0) ? maxLeft : 0;
    newLeft = $('#technical_data_image').position().left-10;
    newLeft = Math.max(newLeft, maxLeft);
    $('#technical_data_image').css('left', newLeft+'px');
    updateTechnicalDataArrows();
    if($('#scrollRight').data('mousedown')) {
        $('#scrollRight').data('iterations', $('#scrollRight').data('iterations')+1);
        setTimeout(technicalDataScrollRight, 20);
    }
}

function technicalDataScrollLeft(){
    newLeft = $('#technical_data_image').position().left+10 < 0 ? $('#technical_data_image').position().left+10 : 0;
    $('#technical_data_image').css('left', newLeft+'px');
    updateTechnicalDataArrows();
    if($('#scrollLeft').data('mousedown')) {
        $('#scrollLeft').data('iterations', $('#scrollLeft').data('iterations')+1);
        setTimeout(technicalDataScrollLeft, 20);
    }
}

function updateTechnicalDataArrows() {
    maxLeft = 715 - $('#technical_data_image').attr('width');
    imgLeft = $('#technical_data_image').position().left;
    if(imgLeft > maxLeft) {
        $('#scrollRight').css('display', '');
        $('#scrollLeft').css('display', '');
    }
    if(imgLeft == maxLeft) {
        $('#scrollRight').css('display', 'none');
        $('#scrollLeft').css('display', '');
    }
    if(imgLeft == 0) {
        $('#scrollLeft').css('display', 'none');
    }
    if(maxLeft > 0) {
        $('#scrollRight').css('display', 'none');
    }
}

function showNextOverview(collection, lang) {
    part_no = $('#overview_'+collection).children().first().attr('part');
    parts_count = $('#overview_'+collection).children().first().attr('parts_count');
    part_no++;
    part_no = part_no > parts_count ? 1 : part_no;
    file = 'data/'+lang+'/products/overview/'+collection+'/'+collection+'_'+part_no+'.html';
    jQuery.get(file, function(data) {
        var loadedImages = 0;
        var imageCount   = $(data).find('.barImg').find('img').length;
//        $(data).find('.barImg').find('img').load(function() {
            loadedImages++;
//            if(loadedImages == imageCount) {
                $('#overview_'+collection).children().first().attr('part', $(data).closest('#main').attr("part"));
                $('#overview_'+collection).find('.barImg').css('opacity', 0);
                $('#overview_'+collection).find('.barItem_link').css('opacity', 0);
                $(data).find('.barItem').each(function() {
                    $('#overview_'+collection).find('.barItem').eq($(this).index()).find('.barImg').html($(this).find('.barImg').html());
                    $('#overview_'+collection).find('.barItem').eq($(this).index()).find('.barItem_link').html($(this).find('.barItem_link').html());
                    $('#overview_'+collection).find('.barItem').eq($(this).index()).attr('class', $(this).attr('class'));
                });
                $('#overview_'+collection).find('.barImg').animate({opacity: 1}, 1000, function(){$(this).css('filter', 'none');});
                $('#overview_'+collection).find('.barItem_link').animate({opacity: 1}, 1000, function(){$(this).css('filter', 'none');});
//            }
//        });
    });
}

function showNextDesignerOverview(lang) {
    part_no = $('#overview_designer').children().first().attr('part');
    parts_count = $('#overview_designer').children().first().attr('parts_count');
    part_no++;
    part_no = part_no > parts_count ? 1 : part_no;
    file = 'data/'+lang+'/designer/overview/designer_'+part_no+'.html';
    jQuery.get(file, function(data) {
        var loadedImages = 0;
        var imageCount   = $(data).find('.barImg').find('img').length;
  //      $(data).find('.barImg').find('img').load(function() {
            loadedImages++;
  //          if(loadedImages == imageCount) {
                $('#overview_designer').children().first().attr('part', $(data).closest('#main').attr("part"));
                $('#overview_designer').find('.barImg').css('opacity', 0);
                $('#overview_designer').find('.barItem_link').css('opacity', 0);
                $(data).find('.barItem').each(function() {
                    $('#overview_designer').find('.barItem').eq($(this).index()).find('.barImg').html($(this).find('.barImg').html());
                    $('#overview_designer').find('.barItem').eq($(this).index()).find('.barItem_link').html($(this).find('.barItem_link').html());
                    $('#overview_designer').find('.barItem').eq($(this).index()).attr('class', $(this).attr('class'));
                });
                $('#overview_designer').find('.barImg').animate({opacity: 1}, 1000);
                $('#overview_designer').find('.barItem_link').animate({opacity: 1}, 1000);
  //          }
  //      });
    });
}

function showNextReferenceOverview(lang) {
    part_no = $('#overview_reference').children().first().attr('part');
    parts_count = $('#overview_reference').children().first().attr('parts_count');
    part_no++;
    part_no = part_no > parts_count ? 1 : part_no;
    file = 'data/'+lang+'/reference/overview/reference_'+part_no+'.html';
    jQuery.get(file, function(data) {
        var loadedImages = 0;
        var imageCount   = $(data).find('.barImg').find('img').length;
    //    $(data).find('.barImg').find('img').load(function() {
            loadedImages++;
    //        if(loadedImages == imageCount) {
                $('#overview_reference').children().first().attr('part', $(data).closest('#main').attr("part"));
                $('#overview_reference').find('.barImg').css('opacity', 0);
                $('#overview_reference').find('.barItem_link').css('opacity', 0);
                $(data).find('.barItem').each(function() {
                    $('#overview_reference').find('.barItem').eq($(this).index()).find('.barImg').html($(this).find('.barImg').html());
                    $('#overview_reference').find('.barItem').eq($(this).index()).find('.barItem_link').html($(this).find('.barItem_link').html());
                    $('#overview_reference').find('.barItem').eq($(this).index()).attr('class', $(this).attr('class'));
                });
                $('#overview_reference').find('.barImg').animate({opacity: 1}, 1000);
                $('#overview_reference').find('.barItem_link').animate({opacity: 1}, 1000);
    //        }
    //    });
    });
}

function displayProductImage(sessLang, imgNo, docID, height) {
    jQuery.get('data/'+sessLang+'/products/detail/'+docID+'_gallery.xml', function(data) {
        data = '<div>'+data+'</div>';
        htmlNode = $(data).find('span').eq(imgNo).clone();
        htmlNode.find('img').removeAttr('height');
        jQuery('#gallery').animate({opacity: '0'}, 1000, function(){
            $('#product_pictures').animate({height: height+'px'}, function(){
                $('#gallery').remove();
                htmlNode.css('opacity', '0');
                htmlNode.insertBefore($('#product_nav'));
                htmlNode.animate({opacity: '1'}, 1000);
                galleryLink = $('<a class="gallery_link" onclick="displayProductGallery(\''+sessLang+'\', \''+docID+'\');return false;" href="index.php?pageID=product_detail_'+sessLang+'&product_detail:productID='+docID+'&product_detail:section=gallery">'+$('body').data('all_images')+'</a>');
                galleryLink.css('opacity', '0');
                $('#product_nav').append(galleryLink);
                if(jQuery.browser.msie) {
                    galleryLink.animate({opacity: '1'});
                }
                else {
                    galleryLink.animate({opacity: '1'});
                }
            });
            
        });
    }, 'XML');
}

function displayProductGallery(sessLang, docID) {

    jQuery.get('data/'+sessLang+'/products/detail/'+docID+'_gallery.html', function(data) {
        $('body').data('all_images', $('.gallery_link').html());
        gallery = $(data).find('#gallery').clone();
        gallery.css({display: 'none'});
        gallery = gallery.insertBefore($('#product_nav'));
        $('#product_pictures').find('img').first().animate({opacity: '0'}, 1000, function() {
            var offset = jQuery.browser.msie ? 80 : 30;
            $('#product_pictures').animate({height: (gallery.height()+offset)+'px'}, function(){
                $('span.overview_image').remove();
                gallery.css('opacity', '0');
                gallery.css('display', '');
                gallery.animate({opacity: '1'}, 1000);
                $('#product_nav').find('a.gallery_link').animate({opacity: '0'}, function(){
                    $(this).remove();
                });
                $('#product_pictures').css('height', 'auto');
            });
        });
    }, 'html');
}

function displayNextProductImage(sessLang, imgNo, docID) {
    jQuery.get('data/'+sessLang+'/products/detail/'+docID+'_gallery.xml', function(data) {
        data = '<div>'+data+'</div>';
        imgNo = imgNo % $(data).find('span').length;
        htmlNode = $(data).find('span').eq(imgNo).clone();
        var span = $('#product_pictures').find('span.overview_image').first();
        var img  = span.find('img').first();
        var newImg = htmlNode.find('a').first();
        span.find('a').css('opacity', 0);
        if(!jQuery.browser.msie) {
            $('#product_pictures').animate({height: newImg.find('img').first().attr('height')+'px'}, function(){
                span.remove();
                newImg.css('opacity', '0');
                htmlNode.insertBefore($('#product_nav'));
                newImg.animate({opacity: '1'}, 1000);
            });
        }
        else {
            $('#product_pictures').css('height', 'auto');
            span.remove();
            newImg.css('opacity', '0');
            htmlNode.find('img').removeAttr('height');
            htmlNode.insertBefore($('#product_nav'));
            newImg.animate({opacity: '1'}, 1000);
        }
    }, 'XML');
}

function displayLookbookImage(pageID, file) {
    $('#lookbook ul').animate({opacity: 0}, function() {
        jQuery.get('index.php?pageID='+pageID+'&lookbook:image='+file+'&template=06_lookbook_single.html&syndicat:view=pre', function(data) {
        //$('#lookbook').css('height', '569px').css('display', 'static').css('overflow', 'visible');
        $('#lookbook').clearQueue();
            $('#lookbook').animate({height: '569px'}, 500, function() {
                var content = $(data).clone();
                content.css('opacity', 0);
                $('#lookbook').html(content);
                content.animate({opacity: 1});
            });
        });
    });
}

function displayLookbookOverview(pageID) {
    jQuery.get('index.php?pageID='+pageID+'&template=06_lookbook_single.html', function(data) {
        content = $(data).clone();
        content.css('opacity', 0);
        $('#lookbook div').animate({opacity: 0}, function() {
            $('#lookbook').html(content);
            $('#lookbook').animate({height: content.height()}, function() {
                content.animate({opacity: 1});
            });
        });
    });
}

function displayNextLookbookImage(pageID, file) {

    
        jQuery.get('index.php?pageID='+pageID+'&lookbook:image='+file+'&template=06_lookbook_single.html&syndicat:view=pre', function(data) {
            var content = $(data);
            var imageCount = content.find('img').length;
            var loadedImages = 0;
            //content.find('img').load(function() {
                loadedImages++;
            //    if(loadedImages == imageCount) {
                    content.find('div.detail_img').css('opacity', 0);
                    content.find('div.title').css('opacity', 0);
                    
                    $('#lookbook').html(content);
                    $('#lookbook div.title').animate({opacity: 1});
                    $('#lookbook div.detail_img').animate({opacity: 1});
            //    }
           // });
    });
}

function displayLookbookTeaser() {
    if($('#lookbook_teaser').css('display') == 'none') {
        $('#lookbook_teaser').css('opacity', '0');
        $('#lookbook_teaser').toggle();
        $('#lookbook_teaser').animate({'opacity': '1'});
    }
    else {
//        $('#lookbook_teaser').css('opacity', '1');      
        $('#lookbook_teaser').animate({'opacity': '0'}, function() {$('#lookbook_teaser').toggle();});
    }
    return false;
}

function showLookbookInfotextProceed() {
    if($('#lookbook_infotext_proceed').data('mouseover') != 'true') {
        $('#lookbook_infotext_proceed').animate({opacity: 1}, function(){
            window.setTimeout(hideLookbookInfotextProceed, 5000);
        });
    }
    else {
        window.setTimeout(showLookbookInfotextProceed, 5000);
    }
}

function hideLookbookInfotextProceed() {
    if($('#lookbook_infotext_proceed').data('mouseover') != 'true') {
        $('#lookbook_infotext_proceed').animate({opacity: 0}, function(){
            window.setTimeout(showLookbookInfotextProceed, 5000);
        });
    }
    else {
        window.setTimeout(hideLookbookInfotextProceed, 5000);
    }
}

function displayStageImage(pageID, imageNo) {
    jQuery.get('index.php?pageID='+pageID+'&content_stage:stageImageNo='+imageNo+'&template=02_stage_single.html&syndicat:view=pre', function(data){
        //$(data).find('img').load(function() {
            $('#conten_stage_image').animate({opacity: 0}, function() {
                $('#conten_stage_image').html(data);
                $('#conten_stage_image').animate({opacity: 1});
            });
        //});
    });
}

function addBrochureFromSidebar(pageID, componentID, section, productID) {
    addBrochure(productID, function() {
        getBrochuresSidebar(pageID, componentID, section, productID);
    });
}

function addAllBrochuresToCart() {
    jQuery.getJSON('brochures_ajax.php',{cmd: 'addAllBrochures'},function(data) {
        jQuery.get('brochures_ajax.php',{cmd: 'getCartSidebar'},function(data_sidebar) {
            for(var i=0;i<data.length;i++) {
                $('#brochure_link_'+data[i]).click();
            }
            //$('#sidebar_order').html(data_sidebar);
        });
    });
}

function addBrochureFromCart(productID) {
    addBrochure(productID, function() {
        $('#brochure_link_'+productID).attr('onclick', '');
        getBrochuresSidebarCart();
        $('#brochure_link_'+productID).addClass('remove_from_cart');
        newTitle = $('#brochure_link_'+productID).attr('alt_title');
        $('#brochure_link_'+productID).attr('alt_title', $('#brochure_link_'+productID).html());
        $('#brochure_link_'+productID).html(newTitle);
        $('#brochure_link_'+productID).unbind().click(function(){removeBrochureFromCartSidebar(productID);return false});
    });
}

function addImageToCart(productID, imageName, elem) {
    addImage(productID, imageName, function() {
        getPressImagesSidebar();
        elem.toggleClass('added');
    });
}

function addImage(productID, imageName, cb) {
    jQuery.getJSON('press_images_ajax.php', {cmd: 'add', productID: productID, imageName: imageName}, function(data){
        cb();
        if(data['count'] == 0) {
            $('#press_image_item_'+productID).find('div.press_image_infotext').first().removeClass('visible');
        }
        else {
            $('#press_image_item_'+productID).find('div.press_image_infotext').first().addClass('visible');
        }
        $('#press_image_item_'+productID).find('div.press_image_infotext').first().html(data['text']);
    });
}

function getPressImagesSidebar() {
    jQuery.get('press_images_ajax.php', {cmd: 'getPressImagesSidebar'}, function(data){
        $('#press_images_sidebar').replaceWith(data);
        //if($('#press_images_sidebar').css('display') == 'none') {
        //    $('#press_images_sidebar').prev().find('a').click();
        //}
    });
}

function addBrochurePartner(productID, count) {
    addBrochureCount(productID, count, function() {
        getBrochuresSidebarCart(true);
    });
}

function removeBrochureFromSidebar(pageID, componentID, section, productID, originProductID) {
    removeBrochure(productID, function() {
        getBrochuresSidebar(pageID, componentID, section, originProductID);
    });
}

function removeBrochureFromCartSidebarPartner(productID) {
    removeBrochure(productID, function() {
        $('#'+productID).find('input[name=brochure_count]').val('0');
        getBrochuresSidebarCart(true);
    });
}

function removeBrochureFromCartSidebar(productID) {
    removeBrochure(productID, function() {
        $('#brochure_link_'+productID).attr('onclick', '');
        getBrochuresSidebarCart();
        $('#brochure_link_'+productID).removeClass('remove_from_cart');
        newTitle = $('#brochure_link_'+productID).attr('alt_title');
        $('#brochure_link_'+productID).attr('alt_title', $('#brochure_link_'+productID).html());
        $('#brochure_link_'+productID).html(newTitle);
        $('#brochure_link_'+productID).unbind().click(function(){addBrochureFromCart(productID);return false});
    });
}

function removeBrochureFromForm(productID, showCount) {
    removeBrochure(productID, function() {
        $('#brochure_'+productID).animate({opacity: 0}, function(){
            $('#brochure_'+productID).animate({width: 0}, function(){
                getBrochuresForm(showCount);
            });
        });
    });
}

function getBrochuresSidebar(pageID, componentID, section, productID) {
    jQuery.get('brochures_ajax.php',
               {pageID: pageID,
                componentID: componentID,
                section: section,
                productID: productID,
                cmd: 'getCartSidebar'
               },
               function(data) {
                    $('#sidebar_order').html(data);
                });
}

function getBrochuresSidebarCart(showCount) {
    jQuery.get('brochures_ajax.php',
               {cmd: 'getCartSidebarCart', showCount: showCount},
               function(data) {
                    $('#sidebar_order').html(data);
                });
}

function getBrochuresForm(showCount) {
    jQuery.get('brochures_ajax.php',
               {
                cmd: 'getCartForm',
                showCount: showCount
               },
               function(data) {
                    $('#brochure_form_header').html(data);
                    if($('.brochure_form_item').length == 0) {
                        $('#brochure_form').hide('blind', function() {$(this).detach();});
                    }
                    $('.brochure_form_item').children('div').hover(function(){
                      $(this).find('a.remove_link').toggle();}, function() {
                      $(this).find('a.remove_link').toggle();
                  });
                  
                  $('.brochureFormClose').toggle();
                });
}

function addBrochure(productID, cb) {
    addBrochureCount(productID, 1, cb);
}

function addBrochureCount(productID, count, cb) {
    jQuery.get('brochures_ajax.php', {cmd: 'add', count: count, productID: productID}, function(data){
        cb();
    });
}

function removeBrochure(productID, cb) {
    jQuery.get('brochures_ajax.php', {cmd: 'remove', productID: productID}, function(data){
        cb();
    });
}

function showAllBrochuresSidebar() {
    $('#sidebar_order').find('tr.hidden').toggleClass('hidden');
    $('#showAllBrochuresSidebar').detach();
}

function addProductFromSidebar(pageID, componentID, section, productID) {
    addProduct(productID, function() {
        getCartSidebar(pageID, componentID, section, productID);
        getCartInfo();
    });
}

function addProductFromLookbook(pageID, componentID, section, productID) {
        addProduct(productID, function() {
        //getCartSidebar(pageID, componentID, section, productID);
        $('#addToCartLink').animate({opacity: 0}, function() {
            var br = $(this).next();
            $(this).detach();
            br.detach();
        });
        getCartInfo();
        return false;
    });
}

function getCartSidebar(pageID, componentID, section, productID) {
    jQuery.get('cart_ajax.php',
               {pageID: pageID,
                componentID: componentID,
                section: section,
                productID: productID,
                cmd: 'getCartSidebar'
               },
               function(data) {
                    $('#sidebar_cart').clearQueue();
                    $('#sidebar_cart').closest('.sidebar_element').replaceWith(data);
                });
    
}

function getCartInfo() {
    jQuery.get('cart_ajax.php',
               {cmd: 'getCartInfo'
               },
               function(data) {
                    if($('#cart_info').length > 0) {
                        $('#cart_info').replaceWith(data);
                    }
                    else {
                        cartinfo = $(data).clone();
                        width = cartinfo.width();
                        cartinfo.css('display', 'none');
                        if($('#mainnav_small').children().length > 0) {
                            cartinfo.insertBefore($('#mainnav_small').children().first());
                        }
                        else {
                            $('#mainnav_small').append(cartinfo);
                        }
                        cartinfo.show('slide');
                    }
                });
}

function addProduct(productID, cb) {
    jQuery.get('cart_ajax.php', {cmd: 'add', productID: productID}, function(data){
        cb();
    });
}

function removeProductFromCart(productID) {
    removeProduct(productID, function(productCount) {
        if(productCount > 0) {
            jQuery.get('cart_ajax.php',
                   {cmd: 'getCartNavigation'},
                   function(data) {
                       $('#brochure_navigation').replaceWith(data);
            });
            $('#product_'+productID).animate({opacity: 0}, function(){ 
                $('#product_'+productID).animate({height: 0}, function() {
                    $('#product_'+productID).detach();
                });
            });
        }
        else {
            jQuery.get('cart_ajax.php',
                   {cmd: 'getCartEmpty'},
                   function(data) {
                       $('#main_product').html(data);
            });
        }
    });
}

function clearCart() {
    jQuery.get('cart_ajax.php', {cmd: 'clear'}, function(data){
        jQuery.get('cart_ajax.php',
           {cmd: 'getCartEmpty'},
           function(data) {
               $('#main_product').html(data);
        });
    });
}

function removeProduct(productID, cb) {
    jQuery.get('cart_ajax.php', {cmd: 'remove', productID: productID}, function(data){
        cb(data);
    });
}

function resetSuggestForm(formAction, productID) {
    jQuery.get('cart_ajax.php', {cmd: 'getSuggestForm', productID: productID, formAction: formAction}, function(data) {
        $('#sidebar_suggest_form').parent().replaceWith(data);
    });
}

