var currentIcon = 0;
var previousIcon = 0;
var currentNews = 1;
var previousNews = 0;
var newsRepeater;
var repeater;
  
$(document).ready(function() {
  
  // Popup leaving site
  
  /*$().onUserExit({
		execute: function() {
		  modal('Server Error', 'Sorry, there was an error on the server. Your vote could not be submitted.');		
			return 'Do you want to take a survey?';
		},
		internalURLs:	"rhythmlink.dev|www.rhythmlink.com|rhythmlink.com"
	});*/


  // Slideshow
 
  size = $("#background-image .slide").length;
  
  $('body.home').not('.intro').queue(function() {
    repeater = $.timer(slideDelay, function(timer) { nextSlide(size); });
  });

  function showSlide(index) {    
    previousIcon = currentIcon;
    currentIcon = index;
    
    if (currentIcon != previousIcon) {
      $(".slide-" + (previousIcon)).fadeOut(1500);
      $(".slide-" + (currentIcon)).fadeIn(1500);
    }
  }
  
  function nextSlide(size) {
    var index = 0;
    
    if(currentIcon < size - 1) {
      index = currentIcon + 1;
    } else {
      index = 0;
    }
    showSlide(index);
  }
  

  // Intro Animation

  jQuery.easing.def = 'easeOutCirc';  
  
  $('body.home.intro').queue(function() {  
    
    if($.browser.msie) {
      $('#logo-ie').animate({'opacity': 1}, 2000, 'easeInCirc', function() {
        $('#logo').show();
        $(this).hide();
        intro();
      });
    } else {
      $('#logo').animate({'opacity': 1}, 2000, 'easeInCirc', intro);    
    }    

  });


  function intro() {
    $('#logo-swirl').animate({left: '0'}, 300, function() {
      $('#logo-green').animate({left: '50%'}, 300, function() {
        $('#background-image').fadeIn(300, function() {
          repeater = $.timer(slideDelay, function(timer) { nextSlide(size); });
          $('#slogan').animate({left: '0'}, 100, function() {
            $('#news').animate({left: '0'}, 100, function() {
              $('#events').animate({right: '0'}, 100, function() {
                $('#poll').animate({right: '0'}, 100, function() {
                  $('.product-catalog-large, .order-now-large').animate({right: '0'}, 100, function() {
                    $('#featured-products').show('fade', {}, 300, function() {
                      $('#boxes').animate({right: '0'}, 100, function() {
                        $('#facebook').animate({right: '0'}, 100, function() {
                          $('#twitter').animate({right: '0'}, 100, function() {
                            $('#linkedin').animate({right: '0'}, 100, function() {
                              $('#youtube').animate({right: '0'}, 100, function() {
                                $('.our-company').animate({top: '0'}, 100, function() {
                                  $('.product-lines').animate({top: '0'}, 100, function() {
                                    $('.custom-solutions').animate({top: '0'}, 100, function() {
                                      $('.customer-support').animate({top: '0'}, 100, function() {
                                        $('.get-in-touch').animate({top: '0'}, 100, function() {
                                          $('#footer, #dots-wrap').fadeIn(500);
                                          popup();
                                        });
                                      });
                                    });
                                  });
                                });                                          
                              });
                            });
                          });
                        });
                      });                         
                    });
                  });
                });
              });
            });              
          });            
        });
      });
    });
  }


  // Show popup on non-home pages
  if($('body.home.intro').length == 0) {
    popup();
  }


  function popup() {
    var action = $('#popup-poll form').attr('action');
    var pollId = action ? getNum(action) : '';
    var date = new Date();
    var today = '' + date.getDate() + date.getMonth() + date.getFullYear();
    
    if(readCookie('popup') != today && ( readCookie('poll-'+pollId) != 'voted' || $('#popup-text').html().length > 5 )) {
      createCookie('popup', today, 1000);
      $('#popup').delay(2000).fadeIn(600);
    }

  }

  // Close popup

  $('#popup-close').click(function() {
    $('#popup').fadeOut();
  });
  

  // Featured Products Slideshow
 
  repeater0 = $.timer(fpDelay1, function(timer) { nextTier(0); });
  repeater1 = $.timer(fpDelay2, function(timer) { nextTier(1); });
  repeater2 = $.timer(fpDelay3, function(timer) { nextTier(2); });
  
  size = [ $('#fp0 img').length,  $('#fp1 img').length,  $('#fp2 img').length ];
  current = [1, 1, 1];
  
  function nextTier(id) {
    $('#fp' + id + ' .fpt' + current[id]).fadeOut(1000);
    
    if(current[id] < size[id]) {
      current[id]++;
    } else {
      current[id] = 1;
    }

    $('#fp' + id + ' .fpt' + current[id]).fadeIn(1000);
  }
  
  
  // News Slideshow
  
  newsRepeater = $.timer(newsDelay, function(timer) { nextNews(); });
  newsSize = $("#news-slides .news-slide").length;
  
  $(".news-thumb").click( function() {
    showNews($(".news-thumb").index(this) + 1);
  });

  $("#news-animation").mouseenter(function(){
    newsRepeater.stop();
  }).mouseleave(function() {
    newsRepeater.reset(newsDelay);
  });

  function showNews(index) {    
    previousNews = currentNews;
    currentNews = index;
    
    var t = index == 1 ? 0 : (index - 1) * 59 - 2;
    var h = (index == 1 || index == 5) ? '53px' : '55px' 
    $('#news-thumbs .active').animate({top: '' + t + 'px', height: h}, 500);
    
    if (currentNews != previousNews) {
      $(".news-slide-" + previousNews).fadeOut(900);
      $(".news-slide-" + currentNews).fadeIn(900);
    }
  }
  
  function nextNews() {
    var index = 0;
    
    if(currentNews < newsSize) {
      index = currentNews + 1;
    } else {
      index = 1;
    }
  
    showNews(index);
  }


  // News Popups

  $('#thumbs .thumb').mouseenter(function() {
    $(this).next().stop(false, true);
    $(this).next().fadeIn(400, function() {
      $(this).children('.quote, .details').animate({width: 350}, 500);
    });
  }).mouseleave(function() {
    $(this).next().stop(false, true);
    $(this).next().children('.quote, .details').animate({width: 0}, 500, function() {
      $(this).parent().fadeOut(400);
    });    
  });
 

  // Main Nav

  $('#main-nav .item').mouseenter(function() {
    $(this).children('.dd').stop(false, true);
    $(this).children('.dd').slideDown();
  }).mouseleave(function() {
    $(this).children('.dd').stop(false, true);
    $(this).children('.dd').slideUp();
  });


  // Subscribe Popup

  $('#subscribe-wrap').mouseenter(function() {
    $(this).stop(false, true);
    $(this).animate({height: 73}, 600);
  }).mouseleave(function() {
    $(this).stop(false, true);
    $(this).animate({height: 32}, 600);
  });


  // Dot Popups

  $('#dots .dot').mouseenter(function() {
    $(this).next().stop(false, true);
    $(this).next().fadeIn(400, function() {
      $(this).children('.quote, .details').animate({width: 350}, 500);
    });
  }).mouseleave(function() {
    $(this).next().stop(false, true);
    $(this).next().children('.quote, .details').animate({width: 0}, 500, function() {
      $(this).parent().fadeOut(400);
    });    
  });



  // News Scrolling

	$("#news .up").click(function() {
	  if( $(this).siblings(".news-items-scroll").attr('scrollTop') <= 130 ) {
	    $(this).hide();
    }
	  if( $(this).siblings(".news-items-scroll").attr('scrollTop') < $(this).siblings(".news-items-scroll").children(".news-items").height() + 260 ) {
	    $("#news .down").show();
    }    

	  $(this).siblings(".news-items-scroll").animate({scrollTop : "-=130px"}, 800, 'easeInOutCubic');
	});

	$("#news .down").click(function() {
	  if( $(this).siblings(".news-items-scroll").attr('scrollTop') >= $(this).siblings(".news-items-scroll").children(".news-items").height() - 260) {
	    $(this).hide();
    }
	  if( $(this).siblings(".news-items-scroll").attr('scrollTop') >= 0 ) {
	    $("#news .up").show();
    }    

	  $(this).siblings(".news-items-scroll").animate({scrollTop : "+=130px"}, 800, 'easeInOutCubic');
	});



  // Default form entry handling

  $('#contact-form textarea').focus(function() {
    if($(this).text() == $(this).attr('default')) {
      $(this).text('');
    }
  });

  if($('#contact-form textarea').text() == '') {
    $('#contact-form textarea').text($('#contact-form textarea').attr('default'));
  }

  $('input.js').focus(function() {
    if($(this).val() == $(this).attr('default')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('default'));
    }
  });

  $('input.js').each(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('default'));
    }  
  });
  
  
  // Product Tables
  
  $('#tiers .tier-header').click(function() {
    var id = getNum($(this).attr('class'));
    if($.browser.msie && parseInt($.browser.version) < 8) {
      $('.tier:visible').not('#tier-' + id).hide();
      $('#tier-' + id).not(':visible').show();
    } else {
      $('.tier:visible').not('#tier-' + id).hide('blind', {}, 500);
      $('#tier-' + id).not(':visible').show('blind', {}, 500);
    }
    $('.tier-details:visible').not('.tier-details-' + id).hide('blind', {}, 500);
    $('.tier-details-' + id).not(':visible').show('blind', {}, 500);
    $('.product-images:visible').not('.product-images-' + id).hide('blind', {}, 500);
    $('.product-images-' + id).not(':visible').show('blind', {}, 500);    
  });

  $('.type').click(function() {
    var id = getNum($(this).attr('class'));
    $(this).siblings().css('text-decoration', 'none');
    $(this).css('text-decoration', 'underline');
    if($.browser.msie && parseInt($.browser.version) < 8) {
      $(this).parent().parent().find('.products:visible').not('.products-' + id).hide();
      $(this).parent().parent().find('.products-' + id).not(':visible').show();
    } else {
      $(this).parent().parent().find('.products:visible').not('.products-' + id).hide('blind', {}, 500);
      $(this).parent().parent().find('.products-' + id).not(':visible').show('blind', {}, 500);
    }
    $(this).parent().parent().find('.colors:visible').not('.colors-' + id).hide('blind', {}, 500);
    $(this).parent().parent().find('.colors-' + id).not(':visible').show('blind', {}, 500);
  });

  
  // Product Samples
  
  $('.product-row.clickable').click(function() {
    $(this).next().toggle(0, function() {
      fleXenv.updateScrollBars(false, false);
    });
  });
  
  
  // Product Images
  
  $('.product-images').each(function(i) {
    var count = $(this).find('.slide').length;
    $(this).find('.d').html(count);
    
    var size = count * 137;
    $(this).find('.product-images-slider').width(size);
  });
    
	$('.img-left').click(function() {
	  if( parseInt($(this).parent().find('.product-images-slider').css('left')) >= -137 ) {
	    $(this).hide();
    }
	  if( parseInt($(this).parent().find('.product-images-slider').css('left')) >= 0 - $(this).parent().find('.product-images-slider').width() - 274 ) {
	    $(this).siblings('.img-right').show();
    }
    
    $(this).parent().find('.n').html(parseInt($(this).parent().find('.n').html()) - 1);

	  $(this).parent().find('.product-images-slider').animate({left : "+=137px"}, 300, 'easeInOutCubic');
	});

	$('.img-right').click(function() {
	  if( parseInt($(this).parent().find('.product-images-slider').css('left')) <= 0 - $(this).parent().find('.product-images-slider').width() + 274) {
	    $(this).hide();
    }
	  if( parseInt($(this).parent().find('.product-images-slider').css('left')) <= 0 ) {
	    $(this).siblings('.img-left').show();
    }
    
    $(this).parent().find('.n').html(parseInt($(this).parent().find('.n').html()) + 1);    

	  $(this).parent().find('.product-images-slider').animate({left : "-=137px"}, 300, 'easeInOutCubic');
	});


  
  /* Old Sample Request Form
  $('#free-samples-form .cancel').click(function() {
    if($.browser.msie && parseInt($.browser.version) < 8) {
      $('#free-samples-form').hide(0, function() {
        $('#tiers').show();
      });
    } else {
      $('#free-samples-form').hide('blind', {}, 500, function() {
        $('#tiers').show('blind', {}, 500);
      });    
    }    
  });
  */
  
  
  // New Samples Request Form  
  
  $('#choose-country .submit-button').click(function() {
    if($('#choose-country .location:checked').val() == 'usa') {
      $('#choose-country').hide('blind', {}, 500);
      $('#chose-usa').show('blind', {}, 500, function() {
        fleXenv.updateScrollBars(false, false);
      });
    }
    if($('#choose-country .location:checked').val() == 'other') {
      $('#choose-country').hide('blind', {}, 500);
      $('#chose-other').show('blind', {}, 500);
      fleXenv.updateScrollBars(false, false);
    }
  });
  
  
  $('#free-samples #product-groups input').click(function() {
    // if > 0 disable all other inputs in tier except in that row
    // if == 0 enable all other inputs in tier
    
    var tr = $(this).parent().parent();
    var tier = $(this).parent().parent().parent().parent().parent().parent().parent();
    
    if($(this).val() > 0) {
      $(tier).find('input').attr('disabled', 'disabled');
      $(tr).find('input').removeAttr('disabled');
    } else {
      $(tier).find('input').removeAttr('disabled');
    }    
    
  });


  // Validate Samples request form and show confirmation page
  
  $('#free-samples .submit-button.review').click(function() {
    $('.required').removeClass('validation-error');
    $('.required').parent().removeClass('validation-error');
    
    var checked = false;
    $('.sample-radio:checked').each(function() {
      if($(this).attr('value') != '0') {
        checked = true;
      }
    });    

    if(!checked) {
      modal('Request Free Samples', 'Please choose some free samples using the product list.');
    } else {

      var errors = false;
      $('#free-samples input.required, #free-samples select.required, #free-samples textarea.required').not('.confirm').each(function() {
        if($(this).val() == '') {
          errors = true;
          $(this).addClass('validation-error');
        }
        
        if($(this).attr('type') == 'radio') {
          var name = $(this).attr('name');
          if($('input[name='+name+']:checked').length == 0) {
            errors = true;
            $(this).parent().addClass('validation-error');
          }
        }
      });
      
      if (errors) {
        modal('Form Error', 'Please fill in all required fields highlighted in red.');
      } else {
      
        $('#free-samples input').not('.required').each(function() {
          if ($(this).val() == $(this).attr('default')) {
            $(this).val('');
          }
        });
        
        $('#free-samples input.text, #free-samples select, #free-samples textarea').each(function() {
          var id = $(this).attr('name');
          var value = $(this).val() == '' ? 'none given' : $(this).val(); 
          $('#step-2 #'+id).html(value);
        });
        
        $('#purchase_number_required').html($('td.purchase-no input:checked').val());
        
        $('#confirm-products tr').not('.th').remove();
        
        $('#product-groups input:checked').each(function() {
          if($(this).val() > 0) {
            var id = getNum($(this).attr('name'));
            $('#confirm-products').append('<tr><td class="left">' + $('#p-'+id).children('.product-no').text() + '</td><td class="right">' + $(this).val() + '</td></tr>');
          }
        });        

        $('.body-content.flexcroll').get(0).fleXcroll.setScrollPos(false, 0);
        
        if($.browser.msie && parseInt($.browser.version) < 8) {
          $('#step-1').hide(0, function() {
            $('#step-2').show(0, function() {
              fleXenv.updateScrollBars(false, false);
            });
          });  
        } else {
          $('#step-1').hide('blind', {}, 500, function() {
            $('#step-2').show('blind', {}, 500, function() {
              fleXenv.updateScrollBars(false, false);
            });
          });  
        } 
        
      }
    
    }
    
    return false;

  });


  $('#free-samples .cancel, #order-form .cancel').click(function() {
    $('.body-content.flexcroll').get(0).fleXcroll.setScrollPos(false, 0);
    
     if($.browser.msie && parseInt($.browser.version) < 8) {
        $('#step-2').hide(0, function() {
          $('#step-1').show(0, function() {
            fleXenv.updateScrollBars(false, false);
          });
        });  
      } else {
        $('#step-2').hide('blind', {}, 500, function() {
          $('#step-1').show('blind', {}, 500, function() {
            fleXenv.updateScrollBars(false, false);
          });
        });  
      }
  }); 
  
  
  $('#free-samples .submit-button.final').click(function() {
      $(this).attr('disabled', 'disabled');

      var action = $('#free-samples').attr('action');
    
      $.post(action, $('#free-samples').serialize(), function(data) {
        if(data == 'success') {
          $('#free-samples .wipe').val('');
          $('.purchase-no input').attr('checked', false);
          $('#free-samples').hide('blind', {}, 500, function() {
            $('.body-content.flexcroll').get(0).fleXcroll.setScrollPos(false, 0);
            $('.success').show('blind', {}, 500);
          });          
        } else if(data == 'failed') {
          $(this).removeAttr('disabled');
          modal('Server Error', 'Sorry, there was an error on the server. Your order could not be submitted.');
        } else {
          $(this).removeAttr('disabled');
          modal('Timeout Error', 'The server took too long to respond, please try again.');
        } 
      });
    
    return false;    
  });


	// Order Form Product Tables

  $('.product-group-header, #product-groups .tier-header').click(function() {
    $(this).next().stop(true, true).toggle('blind', {}, 500, function() {
      fleXenv.updateScrollBars(false, false);
    });
  });

  
  // Order Form Toggle Shipping
  
  $('.toggle-shipping').click(function() {
    if($(this).attr('checked')) {
      $('.ship').attr('disabled', 'disabled');
      $('.shipping').hide();
    } else {
      $('.ship').removeAttr('disabled');
      $('.shipping').show();    
    }
  });


  // Order Form Invoice Delivery
  
  $('.payment-method').change(function() {
    if($(this).attr('checked') == true) {
      if($(this).val() == 'Invoice') {
        $('#invoice-delivery input').removeAttr('disabled');
        $('#invoice-delivery').show(0, function() {
          fleXenv.updateScrollBars(false, false);
        }); 
      } else {
        $('#invoice-delivery input').attr('disabled', 'disabled');
        $('#invoice-delivery').hide(0, function() {
          fleXenv.updateScrollBars(false, false);
        });   
      }
    }
  });


  // Validate Order form and show confirmation page
  
  $('#order-form .submit-button.review').click(function() {
    $('.required').removeClass('validation-error');
    $('.required').parent().removeClass('validation-error');

    var quantity = false;
    $('.quantity-input').each(function() {
      if($(this).attr('value') != '0' && $(this).attr('value') != '') {
        quantity = true;
      }
    });
    
    var errors = false;
    $('input.required, select.required, textarea.required').not(':hidden').each(function() {
      if($(this).val() == '') {
        errors = true;
        $(this).addClass('validation-error');
      }
      
      if($(this).attr('type') == 'radio') {
        var name = $(this).attr('name');
        if($('input[name='+name+']:checked').length == 0) {
          errors = true;
          $(this).parent().addClass('validation-error');
        }
      }
    });
    
    if (errors) {
      modal('Form Error', 'Please fill in all required fields highlighted in red.');
    } else if($('.quantity-input').length > 0 && !quantity) {
      modal('Error: Product Quantities', 'You have not added any products to your order.');
    } else {
    
      $('#order-form input').not('.required').each(function() {
        if ($(this).val() == $(this).attr('default')) {
          $(this).val('');
        }
      });
      
      $('#order-form input.text, #order-form select, #order-form textarea').not('#invoice-delivery-review input').each(function() {
        var id = $(this).attr('name');
        var value = $(this).val() == '' ? 'none given' : $(this).val(); 
        $('#step-2 #'+id).html(value);
      });
      
      $('#shipping_instructions').html($('td.shipping-ins input:checked').val());
      $('#add_to_standing_orders').html($('td.standing-orders input:checked').val());      
      $('#payment_method').html($('td.payment input[name=payment_method]:checked').val());
      
      var pmet = $('.payment-method:checked').val();
      
      if(pmet == 'Invoice') {
        var einv = $('input[name=email_invoice_to]').val();
        if(einv != "") {
          $('#email_invoice_to span').text(einv);
          $('#email_invoice_to').show();
          $('#invoice-delivery-review').show();
        }

        var finv = $('input[name=fax_invoice_to]').val();
        if(finv != "") {
          $('#fax_invoice_to span').text(finv);
          $('#fax_invoice_to').show();
          $('#invoice-delivery-review').show();
        }

        var minv = $('input[name=mail_invoice_to_billing_address]').attr('checked');
        if(minv) {
          $('#mail_invoice_to_billing_address span').text('Yes');
          $('#mail_invoice_to_billing_address').show();
          $('#invoice-delivery-review').show();
        }
      }
      
      $('#confirm-products tr').not('.th').remove();
      
      $('#product-groups input').each(function() {
        if($(this).val() != "") {
          var id = getNum($(this).attr('name'));
          $('#confirm-products').append('<tr><td class="left">' + $('#p-'+id).children('.product-no').text() + '</td><td class="right">' + $(this).val() + '</td></tr>');
        }
      });        

      $('.body-content.flexcroll').get(0).fleXcroll.setScrollPos(false, 0);
      
      if($.browser.msie && parseInt($.browser.version) < 8) {
        $('#step-1').hide(0, function() {
          $('#step-2').show(0, function() {
            fleXenv.updateScrollBars(false, false);
          });
        });  
      } else {
        $('#step-1').hide('blind', {}, 500, function() {
          $('#step-2').show('blind', {}, 500, function() {
            fleXenv.updateScrollBars(false, false);
          });
        });  
      }
      
    }


    return false;

  });

  

  // Submit Order Form using AJAX
  
  $('#order-form .submit-button.final').click(function() {

    $(this).attr('disabled', 'disabled');
    
    var action = $('#order-form').attr('action');
  
    $.post(action, $('#order-form').serialize(), function(data) {
      if(data == 'success') {
        $('#order-form').hide('blind', {}, 500, function() {
          fleXenv.updateScrollBars(false, false);
          $('.success').show('blind', {}, 500);
        });          
      } else if(data == 'failed') {
        $(this).removeAttr('disabled');
        modal('Server Error', 'Sorry, there was an error on the server. Your order could not be submitted.');
      } else {
        $(this).removeAttr('disabled');
        modal('Timeout Error', 'The server took too long to respond, please try again.');
      } 
    });
    
    return false;    
  });


  $('#order-form .submit-button.quote').click(function() {
    $('.required').removeClass('validation-error');
    $('.required').parent().removeClass('validation-error');

    var quantity = false;
    $('.quantity-input').each(function() {
      if($(this).attr('value') != '0' && $(this).attr('value') != '') {
        quantity = true;
      }
    });
    
    var errors = false;
    $('input.required, select.required, textarea.required').not(':hidden').each(function() {
      if($(this).val() == '') {
        errors = true;
        $(this).addClass('validation-error');
      }
      
      if($(this).attr('type') == 'radio') {
        var name = $(this).attr('name');
        if($('input[name='+name+']:checked').length == 0) {
          errors = true;
          $(this).parent().addClass('validation-error');
        }
      }
    });
    
    if (errors) {
      modal('Form Error', 'Please fill in all required fields highlighted in red.');
    } else if($('.quantity-input').length > 0 && !quantity) {
      modal('Error: Product Quantities', 'You have not added any products to your quote.');
    } else {
    
      $('#order-form input').not('.required').each(function() {
        if ($(this).val() == $(this).attr('default')) {
          $(this).val('');
        }
      });

      $(this).attr('disabled', 'disabled');
      
      var action = $('#order-form').attr('action');
    
      $.post(action, $('#order-form').serialize(), function(data) {
        if(data == 'success') {
          $('#order-form').hide('blind', {}, 500, function() {
            fleXenv.updateScrollBars(false, false);
            $('.success').show('blind', {}, 500);
          });          
        } else if(data == 'failed') {
          $(this).removeAttr('disabled');
          modal('Server Error', 'Sorry, there was an error on the server. Your order could not be submitted.');
        } else {
          $(this).removeAttr('disabled');
          modal('Timeout Error', 'The server took too long to respond, please try again.');
        } 
      });      
      
    }

    
    return false;    
  });  

	// Switch between Product Listing & Comments
	
	$('.customer-comments').click(function() {
    $('.customer-comments').css({'z-index': 10}).animate({right: '6px'}, 500);
    $('.product-details').css({'z-index': 9}).animate({right: '-15px'}, 500);

    if($.browser.msie && parseInt($.browser.version) < 8) {
  	  $('.body-content.group:visible').hide(0, function() {
  	    $('.body-content.comments:hidden').show();
  	  });
	  } else {
  	  $('.body-content.group:visible').hide('blind', {}, 500, function() {
  	    $('.body-content.comments:hidden').show('blind', {}, 500);
  	  });	  
    }	  
	    
  });

	$('.product-details').click(function() {
    $('.product-details').css({'z-index': 10}).animate({right: '4px'});
    $('.customer-comments').css({'z-index': 9}).animate({right: '-13px'});

    if($.browser.msie && parseInt($.browser.version) < 8) {
  	  $('.body-content.comments:visible').hide(0, function() {
  	    $('.body-content.group:hidden').show();
  	  });
	  } else {
  	  $('.body-content.comments:visible').hide('blind', {}, 500, function() {
  	    $('.body-content.group:hidden').show('blind', {}, 500);
  	  });
	  }
	  
  });


  // Switch between comments & comment form
  
  $('.leave-comment-header').click(function() {
    $('.comments-list:visible').hide('blind', {}, 500);
    $('.leave-comment:hidden').show('blind', {}, 500);
  });

  $('.comments-list-header').click(function() {
    $('.leave-comment:visible').hide('blind', {}, 500);
    $('.comments-list:hidden').show('blind', {}, 500, function() {
      fleXenv.initByClass('comments-list');
    });
  });


  // Show more comments
  
  $('#read-more').click(function() {
    $(this).hide();
    $('.more-comments').show(0, function() {
      fleXenv.updateScrollBars(false, false);
    });
  });
  
  
  // Terms & Conditions for comments

  $('.terms a').click(function() {
  	$('#terms-dialog').dialog({
  		modal: true,
  		show: 'fade',
  		width: 650,
  		height: 550,
  		resizable: false
    });
    return false;
  });
  
  
  // Validate & Submit comments form using AJAX
  
  $('.leave-comment .submit-button').click(function() {
    $('.required').removeClass('validation-error');
    $('.required').parent().removeClass('validation-error');
    
    var errors = false;
    $('.leave-comment input.required, .leave-comment select.required, .leave-comment textarea.required').not('.confirm').each(function() {
      if ($(this).val() == '' || ($(this).attr('type') == 'checkbox' &&  $(this).attr('checked') == false)) {
        errors = true;
        $(this).addClass('validation-error');
        if($(this).attr('type') == 'checkbox') {
          $(this).parent().addClass('validation-error');
        }
      }
    });
    
    if (errors) {
      modal('Form Error', 'Please fill in all required fields highlighted in red.');
    } else {
    
      $(this).attr('disabled', 'disabled');

      $('.leave-comment input').not('.required').each(function() {
        if ($(this).val() == $(this).attr('default')) {
          $(this).val('');
        }
      });
      
      var action = $('.leave-comment form').attr('action');
    
      $.post(action, $('.leave-comment form').serialize(), function(data) {
        if(data == 'success') {
          $('.leave-comment .wipe').val('');
          $('.agree input').attr('checked', false);
          $('#comment-form').hide('blind', {}, 500, function() {
            $('.leave-comment .success').show('blind', {}, 500);
          });          
        } else if(data == 'failed') {
          $(this).removeAttr('disabled');
          modal('Server Error', 'Sorry, there was an error on the server. Your comment could not be submitted.');
        } else {
          $(this).removeAttr('disabled');
          modal('Timeout Error', 'The server took too long to respond, please try again.');
        } 
      });
      
    }
    
    return false;    
  });


  // Track Analytics for Tiers & Types
  
  $('#content-wrap.product #tiers .tier-header').click(function() {
    var turl = $(this).text().replace(/ /g, '-').toLowerCase();
    var whref = document.location.pathname;
    _gaq.push(['_trackPageview', whref + '/' + turl]);
  });
  
  $('#content-wrap.product #tiers .types .type').click(function() {
    var turl = $(this).text().replace(/ /g, '-').toLowerCase();
    var tierID = getNum($(this).parent().parent().attr('id'));
    var tierName = $('.tier-header-' + tierID).text().replace(/ /g, '-').toLowerCase();
    var whref = document.location.pathname;
    _gaq.push(['_trackPageview', whref + '/' + tierName + '/' + turl]);
  });
  
  
  // Show results if they have already voted
  
  var action = $('#poll form').attr('action');
  var pollId = action ? getNum(action) : '';
  
  if(readCookie('poll-'+pollId) == 'voted') {
    $('#poll .poll-items').hide();
    $('#poll .poll-results').show();
  }

  var action = $('#popup-poll form').attr('action');
  var pollId = action ? getNum(action) : '';
  
  if(readCookie('poll-'+pollId) == 'voted') {
    $('#popup-poll .poll-items').hide();
    $('#popup-poll .poll-results').show();
  }


  // Show results button
  
  $('.quickvote-poll .show-results').click(function() {
    var parent = $(this).parent().parent().parent();
    parent.find('.poll-items').hide('blind', {}, 500);
    parent.find('.poll-results').show('blind', {}, 500);
  });


  // Validate & Submit poll votes
  
  $('.quickvote-poll .submit').click(function() {
  
    var parent = $(this).parent().parent().parent();
    var action = parent.find('form').attr('action');
    var pollId = action ? getNum(action) : '';
    var selection = $('.quickvote-poll input[name=poll]:checked').val();
    
    if(!selection) {
      return false;
    }
    
    if(readCookie('poll-'+pollId) != 'voted') {
      $.post(action, parent.find('form').serialize(), function(data) {
        if(data != 'fail') {
          createCookie('poll-'+pollId, 'voted', 1000);
          parent.find('.poll-results').html(data);
          parent.find('.poll-items').hide('blind', {}, 500);
          parent.find('.poll-results').show('blind', {}, 500);            
        } else if(data == 'fail') {
          $(this).removeAttr('disabled');
          modal('Server Error', 'Sorry, there was an error on the server. Your vote could not be submitted.');
        } else {
          $(this).removeAttr('disabled');
          modal('Timeout Error', 'The server took too long to respond, please try again.');
        } 
      });
    } else {
      parent.find('.poll-items:visible').hide('blind', {}, 500);
      parent.find('.poll-results:hidden').show('blind', {}, 500);      
    }
         
    return false;    
  });


  // Contact Form Accordian
  
  $('.contact-header').click(function() {
    var id = getNum($(this).attr('class'));
    $('.contact-content:visible').not('#contact-content-' + id).hide('blind', {}, 500);
    $('#contact-content-' + id).not(':visible').show('blind', {}, 500);
  });

  
  // Hide Confirm
  
  $('tr.confirm').hide();
  

  // Validate & Submit Contact forms
  
  $('.contact-form').submit(function() {
  
    $('.required').removeClass('validation-error');
    
    var errors = false;
    $(this).find('input.required, textarea.required').not('.confirm').each(function() {
      if ($(this).val() == '') {
        errors = true;
        $(this).addClass('validation-error');
      }
    });
    
    if (errors) {
      modal('Form Error', 'Please fill in all required fields highlighted in red.');
    } else {
    
      $(this).find('.submit-button').attr('disabled', 'disabled');

      $(this).find('input').not('.required').each(function() {
        if ($(this).val() == $(this).attr('default')) {
          $(this).val('');
        }
      });
      
      var theform = this;
    
      $.post($(this).attr('action'), $(this).serialize(), function(data) {
        if(data == 'success') {
          $('.wipe').val('');

          $(theform).hide('blind', {}, 500, function() {
            $(theform).siblings('.success').show('blind', {}, 500);
          });
        } else if(data == 'failed') {
          $(theform).find('.submit-button').removeAttr('disabled');
          modal('Server Error', 'Sorry, there was an error on the server. Your comment could not be submitted.');
        } else {
          $(theform).find('.submit-button').removeAttr('disabled');
          modal('Timeout Error', 'The server took too long to respond, please try again.');
        } 
      });
      
    }
    
    return false;    
  });

});

function getNum(string) {
  return parseInt(string.match(/\d+/));
}

function modal(title, content) {
  $('#alert').html(content);
	$('#alert').dialog({
		modal: true,
		show: 'fade',
		title: title,
    width: 390,
    height: 100,
		resizable: false
  });
}

function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name, "", -1);
}

