// based on http://www.thewebsqueeze.com/forum/Javascript-f66/Jquerysupport-For-Specific-Browsers-t5717.html
if(typeof(browser_IE7) == 'undefined')
  var browser_IE7 = false;

if(typeof $.fn.pause == "undefined") {
  $.fn.pause = function(duration, fnc) {
    $(this).animate({ dummy: 1 }, duration, fnc);
    return this;
  };
}

if(typeof $.fn.outerHTML == "undefined") {
  $.fn.outerHTML = function() {
    return $('<div></div>').append( this.clone() ).html();
  }
}
function center_site(after_ajax){
  if(typeof(after_ajax) == 'undefined')
    after_ajax = false;
  //get total window height - the viewable area of browser
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }

  var siteHeight = $('#all_docsCover').height() + parseInt($('#all_docsCover').css('padding-top')) + parseInt($('#all_docsCover').css('padding-bottom'));
  siteHeight = Math.max(674, siteHeight);

  site_margin_top = (myHeight-siteHeight)/2;
  if(site_margin_top <= 10)
    site_margin_top = 10;

  site_margin_top = Math.round(site_margin_top);

  if(!after_ajax){
    $('#all_docsCover').css('margin-top', site_margin_top+'px');
    $('body').css('background-position', 'center '+(site_margin_top-80)+'px');
  }else{
    $('#all_docsCover').animate({'marginTop': site_margin_top+'px'}, "slow", function(){
      $('body').css('background-position', 'center '+(site_margin_top-80)+'px');
    });
  }
}

$(document).ready(function(){
  //alert('This is updated fade out effect + special product detail loading');
  $('a[href$=.pdf]').live('click', function () {
		pageTracker._trackPageview($(this).attr('href'));
	});
  $('.open-for').live('click', function () {
    $('#'+$(this).attr('for')).slideToggle('slow', function () {
      parent_tag = $($(this).data('parent_tag'));
      if(parent_tag.hasClass('shown')) {
        parent_tag.animate({backgroundColor: '#E99F18', color: '#FFF'});
      } else {
        parent_tag.animate({backgroundColor: '#FFF', color: '#656565'});
      }
      $($(this).data('parent_tag')).toggleClass('shown');
    }).data('parent_tag', $(this).get(0));
  })
  if($('.grey_border_right_no_padding_like_landing_page p, .no_padding_like_landing_page p').find('IMG').length > 0) {
    $('.grey_border_right_no_padding_like_landing_page p, .no_padding_like_landing_page p').each(function () {
      url = $(this).find('A').attr('href');
      if($(this).find('.landing-page-hover-efect').length == 0) {
        tit = $(this).find('IMG').attr('title');
        if(tit.length == 0 && $(this).find('A').length > 0) {
          tit = $('.grey_border_right_no_padding_like_landing_page, .no_padding_like_landing_page', this).find('A').attr('title');
        }
        $('<a class="landing-page-hover-efect" href="'+url+'" style="display: none;"></a>').appendTo(this);
        $('<a class="landing-page-link" href="'+url+'">'+tit+'</a>').appendTo(this);
      }
    })
  }
  $('.related-product-floater').live('mouseover', function () {
    $(this).addClass('mouse-is-over');
  });
  $('.related-product-floater').live('mouseout', function () {
    $(this).removeClass('mouse-is-over');
    $(document).stop('floater-hide');
    $(document).stopTime('floater-show');
    taThis = this;
    $(document).oneTime(100, 'floater-hide', function () {
      if(!($(taThis).hasClass('mouse-is-over') || $('#related_productsBox .mouse-is-over').length > 0)) {
        $(taThis).find('.product-description').slideUp('slow', function () {
          $(taThis).addClass('is-animating').fadeOut('slow', function () {
            $('#related_productsBox .current-floating-info').removeClass('current-floating-info');
            $(this).removeClass('is-animating');
          });
        });
      }
    });
  });
  $('.related-product-container').live('mouseout', function () {
    $(this).removeClass('mouse-is-over');
    $(document).stop('floater-hide');
    $(document).stopTime('floater-show');
    tbThis = this;
    $(document).oneTime(10, 'floater-hide', function () {
      if(!($('.related-product-floater').hasClass('mouse-is-over') || $('#related_productsBox .mouse-is-over').length > 0)) {
        $('.related-product-floater').find('.product-description').slideUp('slow', function () {
          $('.related-product-floater').addClass('is-animating').fadeOut('slow', function () {
            $(this).removeClass('is-animating');
            $(tbThis).removeClass('current-floating-info');
          });
        });
      }
    });
  });

  $('.related-product-container').live('mouseover', function () {
    $(this).addClass('mouse-is-over');
    $(document).stopTime('floater-hide');
    $(document).stopTime('floater-show');
    aThis = this;
    $(document).oneTime(100, 'floater-show', function () {
      if($(aThis).hasClass('mouse-is-over')) {
        position = $('IMG', aThis).offset();
        if($('.related-product-floater').length > 0) {
          container = $('.related-product-floater').html('').fadeOut(0);
          if(container.hasClass('is-shown') && $('#related_productsBox').find('current-floating-info').get(0) == $(this).get(0)) {
            return;
          } else {
            $(this).parents('#related_productsBox').find('.current-floating-info').removeClass('current-floating-info');
          }
        } else {
          container = $('<div class="related-product-floater"></div>').css({position: 'absolute', zIndex: 20}).fadeOut(0);
          container.appendTo('BODY');
        }
        if($(aThis).hasClass('current')) {
          container.addClass('is-current');
        } else {
          container.removeClass('is-current');
        }
        container.append($('INPUT', $(aThis)).val());
        cl = $('IMG', aThis).clone(true);
        container.append($('<a>').attr('href', $('IMG', aThis).parents('A').attr('href')).append(cl));

        tbottom = $(window).height()  - (position.top + $('IMG', aThis).height() + 10);
        container.find('A').address();
        container.css({left: position.left });
        container.css({bottom: tbottom});
        $(aThis).addClass('current-floating-info');
        container.find('.product-description').css({display: 'none'});
        $(container).fadeIn('slow').show();
        $(container).find('.product-description').slideDown('slow');
      }
    })
  })
  center_site();
});

$(window).load(function(){
  center_site();
}).resize(function(){
  center_site();
});


// sollution based on http://www.addthis.com/forum/viewtopic.php?f=8&t=13982&st=0&sk=t&sd=a&start=20
var reinitialize_addthis_count = 0;
function ReinitializeAddThis(){
  reinitialize_addthis_count++;
  //myhref = document.location.href;
  //hash_mark_pos = myhref.indexOf('#');
  //if(hash_mark_pos >= 0)
  //  myhref = myhref.substr(hash_mark_pos).replace(/^([#//]+)/g, '');
  if (window.addthis){
     window.addthis.ost = 0;
     try{
       //window.addthis.ready(); // if loaded sync
       window.addthis.init();    // if loaded async
       //addthis.update('share', 'url', url);
       addthis.update('share', 'title', window.title);
     }catch(err){
       //if( typeof console == 'object' )
       //  console.log('reinitialize_addthis_count: '+reinitialize_addthis_count);
       if(reinitialize_addthis_count<100)
         $(document).oneTime(1000, function(){ReinitializeAddThis();});
     }
  }
}

function ajax_load_url(href, enable_js_redirect, params_url, async_call){
  var result = ' ';
  var title_start_str = 'page_title_start';
  var title_end_str = 'page_title_end';
  if(typeof(enable_js_redirect) != 'boolean')
    enable_js_redirect = true;
  if(typeof(params_url) == 'undefined')
    params_url = '';
  if(typeof(async_call) == 'undefined')
    async_call = true;
  params_url += 'ajax=1';
  hash_mark_pos = href.indexOf('#');
  if(hash_mark_pos >= 0)
    href = href.substr(0, hash_mark_pos);
  $.ajax({
    type: "GET",
    url: href,
    data: params_url,
    async: async_call,
    dataType: "text",
    success: function(response){
      cur_address = $.address.value().replace(/(^\/{0,1})/,"");
      if(async_call && cur_address != href) // if there is already new request - skip the current one
        return;
      result = response;
      title_start_pos = result.indexOf(title_start_str);
      title_end_pos = result.indexOf(title_end_str);
      if((title_start_pos >= 0) && (title_end_pos > 0)){
        title = result.substr(title_start_pos+title_start_str.length, title_end_pos-title_start_pos-title_start_str.length);
        $.address.title(title);
      }
      if(async_call)
        ajax_show_page(result);
    },
    error: function(xhr, desc, exception){ if(enable_js_redirect == true) result = '<script type="text/javascript">location.href="'+href+'"</script>'; }
  });
  if(!async_call)
    return result;
}

$(document).ready(function(){
  //site search input animation
  var $search_input = $('#site_search input#quick_search');
  $search_input.keydown(function(e) {
		if (e.keyCode == 27) {
			$(this).animate({width: 'hide'}, 'slow').addClass('hidden');
		}
	});
  $search_input.addClass('hidden');
  $('#site_search input.submit').click(function(){
    if($search_input.hasClass('hidden')){
      $search_input.animate({width: 'show'}, 'slow', function(){
        $(this).removeClass('hidden').focus();
      });
      return false;
    }else if($search_input.val() == ''){
      alert('Please enter some text you want to search for.');
      $search_input.focus();
      return false;
    }
  });

  $.address.init(function(event) {
  }).change(function(event) {
    //the replace isn't necessary for live site
    url = event.value.replace('/','');
    if((url != '') && ($('.loading').length == 0)){
      url_no_ajax = url.replace('&ajax=1', '');
      is_product_detail_url = false;
      $("#related_products a[href]").each(function(){// product_detail
        if($(this).attr('href') == url_no_ajax && !browser_IE7){ // we have to avoid the IE7 browser because of incorrect rendering
          is_contact_us = $(this).attr('href').indexOf('Contact_Us');
          if(is_contact_us==-1){
            is_product_detail_url = true;
          }else{
            $('.current-floating-info').removeClass('current-floating-info');
            $('.related-product-floater').removeClass('mouse-is-over').remove();
          }
        }
      });

      if(!is_product_detail_url){
        $('#main_menu a, #footer_menu a, #main_menu li, #footer_menu li, #products_menu li, , #products_menu a').removeClass('current').removeClass('submenu_shown');
      }
      $('#products_menu .submenu.copy').remove();
      $('#products_menu ul.submenu').removeClass('dropdown').removeAttr('style');
      $('a[href="'+url+'"]').each(function(){
        $clicked_li = $(this).parent();
        $(this).addClass('current');
        $clicked_li.addClass('current');
        if($clicked_li.parent().hasClass('submenu')){
          $clicked_li.parent().removeAttr('style').removeClass('dropdown').parent().addClass('current');
        }
        //console.log($(this).attr('href'));
      });
      //console.log(event);
      ajax_link(url, is_product_detail_url);//load the link by ajax
    }
  });
  //$('#main_menu a, #footer_menu a, #products_menu a, .landing-page a').address();
  $('#main_menu a, #footer_menu a, #products_menu a, .landing-page a, .press-releases a:not(.remote)').address();

  //products menu functionality
  //show submenu when main products menu link hovered
  $('#products_menu>ul>li>a').mouseenter(function(){
    if(!$(this).parent().hasClass('current')){//if I'm not current get my submenu
      $(this).parent().addClass('submenu_shown');
      submenu = $(this).parent().find('.submenu');
    } else {//I'm current - we need to create a copy of my submenu
      $(this).parent().append('<ul class="submenu copy">'+$(this).parent().find('.submenu').html()+'</ul>');
      submenu = $(this).parent().find('.submenu.copy');
      submenu.find('a').address();//initialize address for the copied submenu
    }
    link_offset_left = $(this).parent().get(0).offsetLeft + parseInt($(this).css('paddingLeft')) - 4;//caclucate left position
    submenu.addClass('dropdown');//this will make submenu look like dropdown
    if((submenu.width()+link_offset_left) > $('#products_menu').width())//if it should be too much on the left
      link_offset_left -= (submenu.width() + link_offset_left - $('#products_menu').width() + 2);//move it so it fits
    submenu.css('left',link_offset_left+'px');
  }).parent().mouseleave(function(){//hide submenu when main products menu li left, bevare - mouseenter is on link, mouseleave is on list item
    if(!$(this).hasClass('current')){
      $(this).find('.submenu').removeClass('dropdown');//this will hide the dropdown
    } else {
      $(this).find('.submenu.copy').remove();//remove copied dropdown
    }
    $(this).removeClass('submenu_shown');//tell me(the list item) I don't have submenu(dropdown) displayed
  });

  after_content_load_events_bind($('body'));


  $('.image-container, .grey_border_right_no_padding_like_landing_page, .no_padding_like_landing_page').live('mouseover', function () {
    $(this).addClass('mouse-is-over');
    $(this).oneTime(10, function () {
      if(($(this).hasClass('mouse-is-over') || $('.landing-page-hover-efect', this).hasClass('mouse-is-over')) && !$('.landing-page-hover-efect', this).hasClass('efect-is-shown')) {
        $('.landing-page-hover-efect', this).show().fadeOut(0).slideDown().addClass('efect-is-shown');
      }
    });
  });
  $('.landing-page-hover-efect').live('mouseover', function () {
    $(this).addClass('mouse-is-over');
  });
  $('.landing-page-hover-efect').live('mouseout', function () {
    $(this).removeClass('mouse-is-over');
  });
  $('.image-container, .grey_border_right_no_padding_like_landing_page, .no_padding_like_landing_page').live('mouseout', function () {
    $(this).removeClass('mouse-is-over');
    $(this).oneTime(100, function () {
      if(!$(this).hasClass('mouse-is-over') && !$('.landing-page-hover-efect', this).hasClass('mouse-is-over')) {
        $('.landing-page-hover-efect', this).slideUp('slow', function () {
          $(this).hide();
        }).removeClass('efect-is-shown');
      }
    });
  });
  //initPressReleases();
});
  function ajax_show_page(pagetext){
    $('#loadingScreen').removeClass('allowStart').stopTime('loadingScreenDisplay').stop(true, true).fadeOut('500');
    contentCover = $('<div>'+pagetext+'</div>').find('#middleCoverContentCover');
    if($("#middleCoverContentCover.hiddenProduct").length == 0){
      // load normal page
      $('#middleCoverContentCover').attr('class',contentCover.attr('class')).html(contentCover.html()).stop(true, true).fadeIn(500, function(){
        after_content_images_load('#middleCoverContentCover');
        init_alternate_images();
        center_site(true);
        $('.landing-page a').address();
      });
      $('.related-product-floater').remove(); // in case that floater does not disapear itself - remove it now anyway.
    }else{ // load product details
      //#product_details, #product_specifications').fadeOut(1000);
      //$('#product_detail_left
      curOpacity = $('#middleCoverContentCover #product_details').css('opacity');
      $('#middleCoverContentCover').removeClass('hiddenProduct');
      $('#middleCoverContentCover #product_details').html($(pagetext).find('#product_details').html()).stop(true, true).fadeTo(500, 1);
      $('#middleCoverContentCover #product_specifications').html($(pagetext).find('#product_specifications').html()).stop(true, true).fadeTo(500, 1);
      $('#product_description, #main_product_imageCover').css('opacity', curOpacity).fadeTo(500, 1); // workaround for IE
      $('#middleCoverContentCover #product_detail_left').html($(pagetext).find('#product_detail_left').html()).stop(true, true).fadeTo(500, 1, function(){
        init_alternate_images();
        center_site(true);
        $('.landing-page a').address();
      });
      after_content_images_load('#middleCoverContentCover');
      //$('#middleCoverContentCover #product_detail_left').after($(pagetext).find('script').outerHTML());
    }
    after_content_load_events_bind($('#middleCoverContentCover'));
  }
  function ajax_link(url, is_product_detail_url){
    $("#middleCoverWhite").css('min-height', $("#middleCoverWhite").height());// store the height of the page
    //$('#middleCoverContentCover').fadeOut("slow", function(){
    url_no_ajax = url.replace('&ajax=1', '');


    if($('#loadingScreen').length == 0)
      $('#middleCoverContentCover').after('<div id="loadingScreen"><img src="http://www.johnbreretonjewellers.ie/site/images/loading_gray_2.gif" alt="loading" style="border: 1px;" /></div>');

    $('#loadingScreen').addClass('allowStart').oneTime(1200, 'loadingScreenDisplay' ,function(){
      if($(this).hasClass('allowStart'))
        $(this).fadeIn('1000');
    });
    if(!is_product_detail_url){
      $('#middleCoverContentCover').fadeOut(1000);
    }else{ // clicked to product related products
      $('#product_details, #product_specifications').fadeTo(1000, 0.001);
      $('#product_detail_left').fadeTo(1000, 0.001);
      $('#product_description, #main_product_imageCover').fadeTo(1000, 0.001);// workaround for IE
      $('#middleCoverContentCover').addClass('hiddenProduct');
      $('#related_products a.current').removeClass('current');
      $('#related_products a[href='+url_no_ajax+']').addClass('current');
    }
    ajax_load_url(url);
    /*
      $('#middleCoverContentCover').html(temp_content).fadeIn(2000, function(){
        console.log("fade in done");
      });
    });
    */
    //$('#middleCoverContentCover').html(ajax_load_url(url)).stop(true, true).fadeIn(2000, function(){
    //  console.log("fade in done");
    //});
/*
      $(this).fadeIn(5000, function(){
        after_content_load_events_bind($(this));
        $images = $(this).find('img');
        if($images.length > 0){
          $images.each(function(){
            $(this).load(function(){
              center_site(true);
            });
          });
        }
        center_site(true);
        $('.landing-page a').address()
      });
    });
    */
  }
function after_content_images_load(parent_elm){
  var myimages = $(parent_elm).find('img');
  if(myimages.length > 0){
    myimages.each(function(){
      $(this).load(function(){
        center_site(true);
      });
    });
  }
}

function after_content_load_events_bind(parent_elm){
  if($('.no_right #middle').length){
    add_scrollbar($('#middle'), 0);
  }else{
    add_scrollbar($('#middle'), 30);
  }
  //add_scrollbar($('#middle'));
  add_scrollbar($('#rightCover'),0,true);

  $(parent_elm).find('a.address').address();

  //close the poupup if it's opened
  $(parent_elm).find('a.address').click(function(){
    if((typeof(popupStatus) != 'undefined') && (typeof(disablePopup) != 'undefined')){
      if(popupStatus == 1)
        disablePopup();
    }
  });

  init_ajax_popups();
  init_ajax_forms();
  init_page_submenu();
  init_more_links(parent_elm);
  $("#middleCoverWhite").css('min-height', '408px');// restore the height of the page

  $(parent_elm).pngFix();

  $(parent_elm).find('input, select, textarea').mouseenter(function(){
    $(this).addClass('hover');
  }).mouseleave(function(){
    $(this).removeClass('hover');
  }).focus(function(){
    $(this).addClass('enter');
  }).blur(function(){
    $(this).removeClass('enter');
  });
  //submit button hover class
  $(parent_elm).find('input.submit').mouseover(function(){
    $(this).addClass('hover');
  }).mouseout(function(){
    $(this).removeClass('hover');
  });

  if($('#middleCoverContentCover #product_details').length){
    reinitialize_addthis_count = 0;
    var script = 'http://s7.addthis.com/js/250/addthis_widget.js?username=johnbreretonjewellers&domready=1&async=1';
    //var script = 'http://s7.addthis.com/js/250/addthis_widget.js#username=johnbreretonjewellers';
    if (window.addthis){
        window.addthis = null;
    }
    $.getScript( script, function(data, textStatus){ReinitializeAddThis();});
  }

  dpval = $('.date-pick').val()
  if(typeof dpval == "undefined" || dpval.length == 0) {
    dpval = '28/01/2010 07:00';
  }
  $('.date-pick').attr('id', 'pickerfield').val(dpval).datetime({
    americanMode: false,
    changeMonth: true,
    changeYear: true,
    firstHour: 9,
    lastHour: 18,
    minuteStep: 15,
    showButtonPanel: true,
    disable_date: false,
    disable_time: true
  });
  $('.time-pick').datetime({
    changeMonth: true,
    changeYear: true,
    firstHour: 9,
    lastHour: 18,
    minuteStep: 15,
    showButtonPanel: true,
    disable_date: true
  });
  $('.landing-page-hover-efect').each(function () {
    if($(this).parent().find('.landing-page-hover-efect-white').length == 0 && ($(this).parents('table.grey_borders').length == 0 || $(this).parents('table.grey_borders.landing-page').length > 0))
      $(this).clone(true).insertBefore(this).removeClass('landing-page-hover-efect').css('display', 'block').addClass('landing-page-hover-efect-white');
  });
  initPressReleases();
  $('a.logo-image-container.openwin').click(function () {
    window.open(this.href);
    return false;
  });
}

function initPressReleases() {
  if((cont = $('.press-releases:not(.links) ul')).length > 0) {
    cont.parent().append($('<div class="middle">').append('<a href="#" onclick="return false;" class="jcarousel-prev">&lt;</a>').append('<a href="#" onclick="return false;" class="jcarousel-next">&gt;</a>'));
    cont.parent().jcarousel({
      scroll: 3,
      itemFallbackDimension: 232,
      wrap: 'circular'
    });
  } else if((cont = $('.press-releases.links ul')).length > 0) {
    cont.parent().append($('<div class="middle">').append('<a href="#" onclick="return false;" class="jcarousel-prev">&lt;</a>').append('<a href="#" onclick="return false;" class="jcarousel-next">&gt;</a>'));
    cont.parent().jcarousel({
      scroll: 1,
      itemFallbackDimension: 716,
      wrap: 'circular'
    });
  }
}
function init_more_links(parent_elm){
  $(parent_elm).find('a.more_link').click(function(){
    var more_link = $(this);
    var more_dots = $(parent_elm).find('#'+more_link.attr('rel')+'_dots');
    var more_content = $(parent_elm).find('#'+more_link.attr('rel'));
    if(more_content.length > 0){
      var shown = more_content.css('display') != 'none';
      if(shown){
        more_dots.fadeIn("fast", function(){
          more_content.fadeOut("slow", function(){
            more_link.html('more');
            if(typeof(center_site) == 'function')
              center_site(true);
          });
        });
      }else{
        more_dots.fadeOut("fast", function(){
          more_content.fadeIn("slow", function(){
            more_link.html(' less');
            if(typeof(center_site) == 'function')
              center_site(true);
          });
        });
      }
      return false;
    }
  });
}

function init_page_submenu(){
  $('ul.page_submenu a.has_submenu').click(function(){
    parent_li = $(this).parent();
    if(!parent_li.hasClass('current')){
      parent_li.toggleClass('submenu_shown').find('ul').slideToggle('slow', function(){
        add_scrollbar('#rightCover', 0, true);
      });
    }
    return false;
  });
}

function init_ajax_forms(){
  $('form.ajax_form').submit(function(){
    if($(this).attr('rel').length > 0){
      var params = '';
  		$(this).find("input:hidden, :text, :checked, :password, :selected, textarea, :submit")
  		.each(function() {
  		  if($(this).attr('name'))
  		    params += $(this).attr('name')+'='+$(this).val()+'&';
  		  else if($(this).parent().attr('name'))
  		    params += $(this).parent().attr('name')+'='+$(this).val()+'&';
  		});
  		var form_result_container = $(this).parent();
  		var form_href = $(this).attr('rel');
  		form_result_container.css({'min-height': form_result_container.height()+'px', '_height': form_result_container.height()+'px', 'min-width': form_result_container.width()+'px', '_width': form_result_container.width()+'px'});
      $('#popupHolder').css({'background-image': "url('/site/images/ajax-loader.gif')"});
      $(this).fadeOut("slow", function(){
  		  form_result_container.html(ajax_load_url(form_href, true, params, false)).fadeIn("slow", function(){
  		    $(this).removeAttr('style');
  		    after_content_load_events_bind(form_result_container);
  		    if(typeof(centerPopup) == 'function')
  		      centerPopup();
  		    $('#popupHolder').css({'background-image': "none"});
        });
      });
  		return false;
    }
  });
}

function init_alternate_images(){
  $('#alternate_images').addClass('hidden');

  $('#alternate_images a')
    .unbind('click')
    .click(function(){
      var clicked_link = $(this);
      if(clicked_link.hasClass('current'))
        return false;
      $('#product_detail_left img#main_product_image').fadeOut("slow", function(){
        $(this).attr('src', clicked_link.attr('href')).fadeIn("slow");
        clicked_link.parent().find('a').toggleClass('current');
      });
      return false;
    });

  $('#main_product_imageCover')
    .unbind('mouseenter mouseleave')
    .hover(
      function(){
        if(!$('#alternate_images').hasClass('shown'))
          $('#alternate_images').addClass('shown').fadeIn();
      },
      function (){
        if($('#alternate_images').hasClass('shown'))
          $('#alternate_images').removeClass('shown').fadeOut();
      }
    );
}

var loaded_images = 0;
function loaded_image(){
  //console.log('loaded_image: '+loaded_images);
  loaded_images++;
  if(loaded_images == related_products_array.length){
    //console.log('loaded_images all');
    //alert('loaded_images all');
    $('#related_productsBox a').address();
    $('#related_productsBox').jScrollHorizontalPane({showArrows:true,arrowSize:10,scrollbarHeight:11,scrollbarMargin:0})
    .bind(
      'scroll',
      function(event){
        $(document).stop('floater-hide');
        $(document).stopTime('floater-show');
        //$('.related-product-floater').stop().slideUp().removeClass('is-animating').hide().css({opacity:1});
        $('.related-product-floater').remove();
      }
    );

    scroll_to = 0;
    if($('#related_productsBox').find('a.current').length > 0)
      scroll_to = $('#related_productsBox').find('a.current')[0].offsetLeft - $('#related_productsBox').find('a.current').width();
    if(scroll_to > 0)
      $('#related_productsBox')[0].scrollTo(scroll_to);
    // hide current floater as it might not be actual
    $('.related-product-floater').pause(1000).addClass('is-animating').fadeOut('slow').removeClass('is-animating');
  }
  //$('#related_productsCover > span').remove();
  //$('#related_productsCover').append('<span class="spacer"> </span>');
}

function load_related_products(index){

  if(typeof(related_products_array) == 'undefined')
    return;
  if(related_products_array.length == 0)
    return;
  if(typeof(index) == 'undefined')
    index = 0;

  //if(index == 0){
  loaded_images = 0;
  for (var i = 0; i < related_products_array.length; i++) {
    link_class = '';
//    if((typeof(current_product_url) != 'undefined') && (current_product_url == related_products_array[i]['url']))
    if((typeof(current_product_url) != 'undefined') && (related_products_array[i]['url'].indexOf(current_product_url+'*') != -1))
      link_class = 'current';
    link_class += (link_class.length > 0 ? ' ' : '') + 'related-product-container';
    $('#related_productsBox')
      .append('<a class="'+link_class+'" href="'+related_products_array[i]['url']+'"><img style="width: 150px;" src="'+related_products_array[i]['image']+'" alt="" id="related_product_image_'+i+'" /><input type="hidden" class="product-description-container" value=\''+related_products_array[i]['description'].replace(/\'/g, "\\\'")+'\' /></a>');
	}
  $('#related_productsBox img').load(function(){
    loaded_image();
  });



  //$('#related_productsBox').pause(200, function(){
  //});


/*
  if(typeof(related_products_array[index]) == 'undefined'){
    $('#related_productsBox a').address();
    $('#related_productsBox').jScrollHorizontalPane({showArrows:true,arrowSize:10,scrollbarHeight:11,scrollbarMargin:0});
    scroll_to = 0;
    if($('#related_productsBox').find('a.current').length > 0)
      scroll_to = $('#related_productsBox').find('a.current')[0].offsetLeft - $('#related_productsBox').find('a.current').width();
    if(scroll_to > 0)
      $('#related_productsBox')[0].scrollTo(scroll_to);
    return;
  }

  link_class = '';
  if((typeof(current_product_url) != 'undefined') && (current_product_url == related_products_array[index]['url']))
    link_class = 'current';

  $('#related_productsBox')
    .append('<a class="'+link_class+'" href="'+related_products_array[index]['url']+'"><img src="'+related_products_array[index]['image']+'" alt="" id="related_product_image_'+index+'" /></a>')
    .find('#related_product_image_'+index).load(function(){
      load_related_products(index+1);
    });
*/
}

function openPrintWindow(url){
  attrib = "width=600,height=780,menubar=yes,personalbar=no,titlebar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes";
  win = window.open(url, 'name', attrib);
}

function update_make_an_appointment_link_text(products_selected){
  if(typeof(products_selected) == 'undefined')
    products_selected = 0;
  products_selected = parseInt(products_selected);
  link_text = 'Make an Appointment';
  if(products_selected > 0)
    link_text += '&nbsp;('+products_selected+')';
  $('#top_banner, #footer_menu').find('a[href*="Make_an_Appointment"]').html(link_text);
}

function add_scrollbar(parent_elm, scrollbarMarginPx, force_display){
  if($(parent_elm).length == 0)
    return;
  if($(parent_elm).find('#product_detail').length > 0){
    // for product details - allow scrolling in the product description
    if(typeof(force_display) == 'undefined'){
      var new_min_height = 196 - $(parent_elm).find('#product_detail h2').height() - $(parent_elm).find('#product_detail h1').height();
      $('#product_description').css('minHeight', new_min_height+'px');
      add_scrollbar($('#product_description'), 16, true); // throwing an exeption when showing scroller !!!
      return;
    }
  }
  if($('#middleCoverContentCover').hasClass('homepage'))//we don't want scrollbars on homepage
    return;
  if(scrollbarMarginPx == 'undefined')
    var scrollbarMarginPx = 0;
  var height = 0;
  var width = 0;
  var padding_right_new = 7;
  var padding_right = 7;
  if(parseInt($(parent_elm).css('minHeight')) > 0)
    height = parseInt($(parent_elm).css('minHeight'));
  if(parseInt($(parent_elm).css('width')) > 0){
    width = parseInt($(parent_elm).css('width')) - padding_right_new;
    if(parseInt($(parent_elm).css('paddingRight')) > 0)
      width += parseInt($(parent_elm).css('paddingRight')) - padding_right_new;
  }
  client_height = $(parent_elm).get(0).clientHeight;
  if(force_display==true || ((height > 0) && (client_height > height+padding_right_new+padding_right_new) && (width > 0))){
    if(parseInt($(parent_elm).css('paddingRight')) > 0)
      $(parent_elm).css('paddingRight', padding_right_new+'px');
    if($(parent_elm).find('.jScrollPaneWrapper').length == 0)
      $(parent_elm).html('<div class="jScrollPaneWrapper">'+$(parent_elm).html()+'</div>');
    $(parent_elm).find('.jScrollPaneWrapper')
    .css({
      width: width + 'px',
      height: height + 'px'
    })
    .jScrollPane({
      showArrows:true,
      arrowSize:11,
      scrollbarWidth:11,
      scrollbarMargin:scrollbarMarginPx,
      reinitialiseOnAllImageLoad:true
    });
  }
}



function printStackTrace() {
  var callstack = [];
  var isCallstackPopulated = false;
  try {
    i.dont.exist+=0; //doesn't exist- that's the point
  } catch(e) {
    if (e.stack) { //Firefox
      var lines = e.stack.split("\n");
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          callstack.push(lines[i]);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
    else if (window.opera && e.message) { //Opera
      var lines = e.message.split("\n");
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          var entry = lines[i];
          //Append next line also since it has the file info
          if (lines[i+1]) {
          entry += " at " + lines[i+1];
          i++;
          }
          callstack.push(entry);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
  }

  if (!isCallstackPopulated) { //IE and Safari
    var currentFunction = arguments.callee.caller;
    while (currentFunction) {
      var fn = currentFunction.toString();
      var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
      callstack.push(fname);
      currentFunction = currentFunction.caller;
    }
  }
  output(callstack);
}

function output(arr) {
  //Output whatever you want
  alert('stack trace'+ arr.join("\r\n"));
}
