/**
 * tablePagination - A table plugin for jQuery that creates pagination elements
 *
 * http://neoalchemy.org/tablePagination.html
 *
 * Copyright (c) 2009 Ryan Zielke (neoalchemy.com)
 * licensed under the MIT licenses:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @name tablePagination
 * @type jQuery
 * @param Object settings;
 *      firstArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/first.gif"
 *      prevArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/prev.gif"
 *      lastArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/last.gif"
 *      nextArrow - Image - Pass in an image to replace default image. Default: (new Image()).src="./images/next.gif"
 *      rowsPerPage - Number - used to determine the starting rows per page. Default: 5
 *      currPage - Number - This is to determine what the starting current page is. Default: 1
 *      optionsForRows - Array - This is to set the values on the rows per page. Default: [5,10,25,50,100]
 *      ignoreRows - Array - This is to specify which 'tr' rows to ignore. It is recommended that you have those rows be invisible as they will mess with page counts. Default: []
 *
 *
 * @author Ryan Zielke (neoalchemy.org)
 * @version 0.2
 * @requires jQuery v1.2.3 or above
 */

 (function($){

	$.fn.tablePagination = function(settings) {
		var defaults = {  
			firstArrow : (new Image()).src="./images/first.gif",  
			prevArrow : (new Image()).src="./images/prev.gif",
			lastArrow : (new Image()).src="./images/last.gif",
			nextArrow : (new Image()).src="./images/next.gif",
			rowsPerPage : 5,
			currPage : 1,
			optionsForRows : [5,10,25,50,100],
			ignoreRows : []
		};  
		settings = $.extend(defaults, settings);
		
		return this.each(function() {
      var table = $(this)[0];
      var totalPagesId, currPageId, rowsPerPageId, firstPageId, prevPageId, nextPageId, lastPageId
      if (table.id) {
        totalPagesId = '#'+table.id+'+#tablePagination #tablePagination_totalPages';
        currPageId = '#'+table.id+'+#tablePagination #tablePagination_currPage';
        rowsPerPageId = '#'+table.id+'+#tablePagination #tablePagination_rowsPerPage';
        firstPageId = '#'+table.id+'+#tablePagination #tablePagination_firstPage';
        prevPageId = '#'+table.id+'+#tablePagination #tablePagination_prevPage';
        nextPageId = '#'+table.id+'+#tablePagination #tablePagination_nextPage';
        lastPageId = '#'+table.id+'+#tablePagination #tablePagination_lastPage';
      }
      else {
        totalPagesId = '#tablePagination #tablePagination_totalPages';
        currPageId = '#tablePagination #tablePagination_currPage';
        rowsPerPageId = '#tablePagination #tablePagination_rowsPerPage';
        firstPageId = '#tablePagination #tablePagination_firstPage';
        prevPageId = '#tablePagination #tablePagination_prevPage';
        nextPageId = '#tablePagination #tablePagination_nextPage';
        lastPageId = '#tablePagination #tablePagination_lastPage';
      }
      
      var possibleTableRows = $.makeArray($('tbody tr', table));
      var tableRows = $.grep(possibleTableRows, function(value, index) {
        return ($.inArray(value, defaults.ignoreRows) == -1);
      }, false)
      
      var numRows = tableRows.length
      var totalPages = resetTotalPages();
      var currPageNumber = (defaults.currPage > totalPages) ? 1 : defaults.currPage;
      if ($.inArray(defaults.rowsPerPage, defaults.optionsForRows) == -1)
        defaults.optionsForRows.push(defaults.rowsPerPage);
      
      
      function hideOtherPages(pageNum) {
        if (pageNum==0 || pageNum > totalPages)
          return;
        var startIndex = (pageNum - 1) * defaults.rowsPerPage;
        var endIndex = (startIndex + defaults.rowsPerPage - 1);
        $(tableRows).fadeIn('slow');
        for (var i=0;i<tableRows.length;i++) {
          if (i < startIndex || i > endIndex) {
            $(tableRows[i]).hide()
          }
        }
      }
      
      function resetTotalPages() {
        var preTotalPages = Math.round(numRows / defaults.rowsPerPage);
        var totalPages = (preTotalPages * defaults.rowsPerPage < numRows) ? preTotalPages + 1 : preTotalPages;
        if ($(totalPagesId).length > 0)
          $(totalPagesId).html(totalPages);
        return totalPages;
      }
      
      function resetCurrentPage(currPageNum) {
        if (currPageNum < 1 || currPageNum > totalPages)
          return;
        currPageNumber = currPageNum;
        hideOtherPages(currPageNumber);
        $(currPageId).val(currPageNumber);
		$('#tablePagination_currPage').text(currPageNum);
      }
      
      function resetPerPageValues() {
        var isRowsPerPageMatched = false;
        var optsPerPage = defaults.optionsForRows;
        optsPerPage.sort(function (a,b){return a - b;});
        var perPageDropdown = $(rowsPerPageId)[0];
        perPageDropdown.length = 0;
        for (var i=0;i<optsPerPage.length;i++) {
          if (optsPerPage[i] == defaults.rowsPerPage) {
            perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i], true, true);
            isRowsPerPageMatched = true;
          }
          else {
            perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i]);
          }
        }
        if (!isRowsPerPageMatched) {
          defaults.optionsForRows == optsPerPage[0];
        }
      }
      
      function createPaginationElements() {
        var htmlBuffer = [];
        htmlBuffer.push("<div id='tablePagination'>");
        htmlBuffer.push("<span id='tablePagination_perPage' style='visibility:hidden;'>");
        htmlBuffer.push("<select id='tablePagination_rowsPerPage'><option value='5'>5</option></select>");
        htmlBuffer.push("per page");
        htmlBuffer.push("</span>");
        htmlBuffer.push("<span id='tablePagination_paginater'>");
        htmlBuffer.push("<span id='tablePagination_firstPage'> &nbsp; </span>");
        htmlBuffer.push("<span id='tablePagination_prevPage'> &nbsp; </span>");
        htmlBuffer.push("PAGE&nbsp; ");
        htmlBuffer.push("<span id='tablePagination_currPage'>"+currPageNumber+"</span>");
        htmlBuffer.push("&nbsp;of <span id='tablePagination_totalPages'>"+totalPages+" </span>");
        htmlBuffer.push("<span id='tablePagination_nextPage'> &nbsp; </span>");
        htmlBuffer.push("<span id='tablePagination_lastPage'> &nbsp; </span>");
        htmlBuffer.push("</span>");
        htmlBuffer.push("</div>");
        return htmlBuffer.join("").toString();
      }
      
      if ($(totalPagesId).length == 0) {
        $(this).after(createPaginationElements());
      }
      else {
        $('#tablePagination_currPage').val(currPageNumber);
      }
      resetPerPageValues();
      hideOtherPages(currPageNumber);
      
      $(firstPageId).bind('click', function (e) {
        resetCurrentPage(1)
      });
      
      $(prevPageId).bind('click', function (e) {
        resetCurrentPage(currPageNumber - 1)
      });
      
      $(nextPageId).bind('click', function (e) {
        resetCurrentPage(currPageNumber + 1)
      });
      
      $(lastPageId).bind('click', function (e) {
        resetCurrentPage(totalPages)
      });
      
      $(currPageId).bind('change', function (e) {
        resetCurrentPage(this.value)
      });
      
      $(rowsPerPageId).bind('change', function (e) {
        defaults.rowsPerPage = parseInt(this.value, 10);
        totalPages = resetTotalPages();
        resetCurrentPage(1)
      });
      
		})
	};		
})(jQuery);

/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);


/**
 * Custom script by infront web for implementing the image swap and pagination functionality
 *
 * by www.infrontweb.com
 */
$(function(){
	//script for changing of the product image correspong the thumbnial clicked	   
	$('input[type=radio].attr_radio').click(swap_image);
	$('td.rb_oll_label img').css('cursor','pointer').click(click_radio);
	
	//script to make the first radio button get defaultly selected on page load
	var f_radio = $('input[type=radio].attr_radio').first();
	var f_th_title = f_radio.attr('value');
	var f_big_title = f_th_title.replace(/-/g,' ');
	$('div.product-image').next('h1').text(f_big_title);
	f_radio.attr('checked','checked');
	
	//script to add the pagination to the product display
	$('.attr_radio_table:first').tablePagination({
		rowsPerPage  : 3,
		ignoreRows : $('.attr_radio_table table tr')
	})
	
	//script to add the tooltip
	$('td.rb_oll_label img').tooltip({ 
    								delay: 250,
									track: true,
									fade: 250,
    								showURL: false, 
    								bodyHandler: function() { 
        								var tipname = $(this).parent('td').parent('tr').next('tr').find('td.rb_oll_radio').find('input.attr_radio').val().split('-');
										return tipname[0];
										 
    								}
								});
	
});

//function to swap image of the main product page when a radio or image thumb is clicked
function swap_image(){
	var radio = $(this);
	var th_image = radio.attr('OptionImage');
	var big_image = th_image.replace('-th.jpg', '-lg.jpg');
	var th_title = radio.attr('value');
	var big_title = th_title.replace(/-/g,' ');
	$('div.product-image').addClass('ajax_loading');
	$('div.product-image').next('h1').text(big_title);
	var prod_image = $('div.product-image img:first-child');
	prod_image.fadeOut('fast',function(){ 
				$('div.product-image').addClass('ajax_loading');
				$(this).attr('src',big_image).load(function(){ 
						$('div.product-image').removeClass('ajax_loading');
						$(this).fadeIn('slow')}
				)}
	);
	
}

//function to click on first radio button for default display
function click_radio(){
	
	$(this).parent('td').parent('tr').next('tr').find('td.rb_oll_radio').find('input.attr_radio').click();
	
}
