// joe's js

var numthumbs=$("#pp-photos #thumbs > li").size();
if (numthumbs>1) { $('#photo a').removeClass('cloud-zoom'); }
if (!$("select#search_color").hasClass("only-option")) { $('#photo a').removeClass('cloud-zoom'); }
if ($.browser.msie && $.browser.version.substr(0,1)<9) { $('#photo a').removeClass('cloud-zoom'); }

	
$(document).ready(function() {
						   
	$('.Left.Handed:not(.Gloves) #pp-photos').prepend('<div class="lefty-icon"></div>');
	
	$("#pp-wrap:not(.Complete) .headcover-note").parent().css("border", "0").css("margin", "0").insertAfter($("#pp-sku-id"));
	$(".Complete .headcover-note").css("padding", "10px").insertAfter($("#pp-sku-id"));
	//$(".headcover-note").parent().css("border", "0").css("margin", "0").insertAfter($("#condition-specs"));
	//$(".Complete .headcover-note").css("padding", "10px").insertAfter($("#other-specs"));
	$(".Complete #other-specs").addClass("border");
	
	$(".specs-box").fadeIn("slow");
	$(".cond-link").append($(".grips-option"));
	
	$specsHeight = $("#pp-specs").height();
	$("#pp-specs").height($specsHeight);

	$("select").change(function () {
		$(".specs-box").hide().fadeIn("slow");
	})

	$(".stylethumb").click(function () {
		if ($(this).hasClass('inactive')) {
			return false;
		}
		$(".specs-box").hide().fadeIn("slow");
	})

	$("#style_num_reset").click(function () {
		$(".specs-box").hide().fadeIn("slow");
	})

	$("#pp-specs").css("background-image","none");
	
	$('#other-specs .headcover-note').fadeIn();
	
	// Product Demo/Tour Button
	$('span#easy2Container_tbal_610').clone().prependTo('#fnb-content');
	
	if (!$("select#search_color").hasClass("only-option")) {
		$(".Apparel .more-colors, .Bag .more-colors, .Gloves .more-colors, .Shoes .more-colors, .Socks .more-colors").show();
	}
	
	// Turn off twitter from wikiconnect
	RunPWConnect('.ProductWikiConnect', { disabledmodules: 'twitter'});
});

function update_current_selections(selected_config_type){

	// Resets
	/*if (selected_config_type != 'style_num' && $('#search_' + selected_config_type + ' option:selected').val() == 'none') {
		$('#styleselect .overview .stylethumb').each(function() {
			$(this).removeClass('active');
			$(this).removeClass('inactive');
		});
	}*/

	for(i=0;i<current_selection_data.length;i++){
		field = 'search_'+current_selection_data[i][0];
		if (field == 'search_style_num') {
			var value = 'none';
			// Find active thumb
			var active_style = $('#styleselect .overview').find('.active:first');
			if (active_style.length > 0) {
				var image = active_style.find('img');
				if (image.length > 0) {
					value = image.attr('title');
				}
			}

		} else {
			value = document.getElementById(field).options[document.getElementById(field).selectedIndex].value;

			if( selected_config_type != undefined && current_selection_data[i][0] != selected_config_type && current_selection_data[i][3] == 'auto') {
				value = 'none';
			}
		}

		current_selection_data[i][1] = value;

		if( current_selection_data[i][0] == selected_config_type ) {
			if( value == '' || value == 'none' ) {
				current_selection_data[i][3] = 'auto';
			} else {
				current_selection_data[i][3] = 'set';
			}
		}
	}
}

function update_thumb_selectors(thumb_id) {
	var config_type = 'style_num';
	var thumb = $('#' + thumb_id);
	if (thumb.length > 0) {
		if (thumb.hasClass('inactive')) {
			return false;
		} else {
			// Remove previous active thumb
			$('#styleselect .overview .stylethumb').each(function() {
				$(this).removeClass('active');
			});
			// Make current selected active
			thumb.removeClass('inactive');
			thumb.addClass('active');
			update_selectors(config_type);
		}
	}
}

function style_num_thumbs_reset() {
	var config_type = 'style_num';
	$('#styleselect .overview .stylethumb').each(function() {
		$(this).removeClass('active');
		$(this).removeClass('inactive');
	});
	update_selectors(config_type);
}

function style_num_make_only_thumb_active() {
return true;
	var thumb = $('#styleselect .overview .stylethumb:not(.inactive)');
	if (thumb.length == 1) {
		thumb.removeClass('inactive');
		thumb.addClass('active');
	}
}

function update_selectors(selected_config_type)
{
	var config_type;
	var sandu_id;
	var selected;
	var size;
	
	update_current_selections(selected_config_type);
	for (config_type in all_options) {
		size = 0;
		i=0;
		show_options = new Array();
		empty_menus(config_type);
		for (sandu_id in all_options[config_type]) {
			available = check_availability(sandu_id, config_type);
			if (available == 'in_stock' || all_options[config_type][sandu_id][1] == '' || all_options[config_type][sandu_id][1] == 'none') {
				// this is an option we need to draw!
				show_options[i] = all_options[config_type][sandu_id];
				i++;
			}
			if( available == 'in_stock' && all_options[config_type][sandu_id][1] != '' && all_options[config_type][sandu_id][1] != 'none') {
				size++;
			}
		}

		for( i=0; i<show_options.length; i++ ) {
			this_option = show_options[i];
			if( size == 1 && (this_option[1] == '' || this_option[1] == 'none') ) {
				continue;
			}
			
			add_option_to_menu(this_option, selected_config_type);
		}
		
		update_num_options_element = $("#number_options_"+config_type);
		if( update_num_options_element ) {
			number_options_message = "(" + size + " option";
			if( size > 1 ) {
				number_options_message += "s";
			}
			number_options_message += ")";
			update_num_options_element.html(number_options_message);
		}

		$("#search_" + config_type).toggleClass("only-option", (size == 1));
	}
	
	style_num_make_only_thumb_active();
	update_product_information();
}


function empty_menus(config_type) {
	if (config_type == 'style_num') {
		$('#styleselect .overview .stylethumb').each(function() {
			$(this).removeClass('active');
			$(this).addClass('inactive');
		});
	} else {
		var config_selection_string = 'search_'+config_type;
		var config_selector = document.getElementById(config_selection_string);
		var sandu_id;
		config_selector.length = 0;
	}
}

function add_option_to_menu(menu_info, selected_config_type){
	var option;
	var selected = false;
	var has_selection = true;
	var i;
	var selection_name;
	for (i=0;i<current_selection_data.length;i++) {
		if( current_selection_data[i][0] == menu_info[0] ) {
			selection_name = current_selection_data[i][2];
			if( current_selection_data[i][1] == menu_info[1] ) {
				selected = true;
			}
			if( current_selection_data[i][1] == 'none' || current_selection_data[i][1] == '' ) {
				has_selection = false;
			}
			break;
		}
	}

	if (menu_info[0] == 'style_num') {
		var style_num_reset = $('#style_num_reset');
		var thumb = $('#thumb_' + menu_info[1]);
		// Make available
		thumb.removeClass('active');
		thumb.removeClass('inactive');
		if (has_selection) {
			// Add reset link
			style_num_reset.html('&nbsp;<a href="javascript:void(0);" onclick="style_num_thumbs_reset()">Reset Style</a>');
			// Make selected active
			if (selected) {
				thumb.addClass('active');
			}
		} else {
			// Remove reset link
			style_num_reset.html('');
		}

	} else {
		if (menu_info[1] == 'none' || menu_info[1] == '') {
			if (has_selection) {
				option = new Option('Reset ' + selection_name + '...', 'none', false);
			}
			else {
				option = new Option(menu_info[2], menu_info[1], false);
				option.selected = true;
			}
		}
		else {
			option = new Option(menu_info[2], menu_info[1], false);
			option.selected = selected;
		}

		// add option to menu
		try {
			document.getElementById('search_' + menu_info[0]).add(option,null);
		} catch(e) {
			document.getElementById('search_' + menu_info[0]).add(option);
		}
	}
}

function check_availability(config_id, config_type) {
	var i, j, k, l;
	var sku_id;
	var current_type;
	var config_skus = available_options[config_type][config_id];
	var config_skus_updated = Array();
	var available = 'in_stock';
	var exists_here;

	if (all_options[config_type][config_id][3] == 0) {
		return available;
	}

	i=0;
	for (sku_id in config_skus) {
		config_skus_updated[i] = sku_id;
		i++;
	}

	// check each selected option in turn
	for (i=0;i<current_selection_data.length;i++) {
		if (i == 'indexOf' || current_selection_data[i][1] == 'none' || current_selection_data[i][1] == '') {
			// skip if no option selected
			continue;
		}
		current_type = current_selection_data[i][0];
		selected_config = current_selection_data[i][1];
		if (current_type == config_type) {
			// skip if checking against this selection
			continue;
		}

		// set current availability and reset updated availability
		config_skus = config_skus_updated;
		config_skus_updated = Array();
		l = 0;

		// look for any skus in selected type that have passed all previous selection tests
		for (j in available_options[current_type][selected_config]) {
			for (k in config_skus) {
				if (config_skus[k] == j) {
					config_skus_updated[l] = config_skus[k];
					l++;
				}
			}
		}

		// option is unavailable if no skus pass at any test
		if( config_skus_updated.length < 1 ) {
			available = 'unavailable';
			break;
		}
	}
	return available;
}

function update_product_availability() {
	update_current_selections();

	var number_available = 0;
	var all_selected = true;

	for(i in product_availability) {
		product_availability[i][1] = 1;
		number_available++;
	}

	for(i in current_selection_data ) {
		if (i == 'indexOf' || current_selection_data[i][1] == 'none' || current_selection_data[i][1] == '') {
			all_selected = false;
			continue;
		}

		config_type = current_selection_data[i][0];
		selected_option = current_selection_data[i][1];

		for(option in available_options[config_type]) {
			if( option != selected_option ) {
				for(model_id in available_options[config_type][option]) {
					for(j in product_availability) {
						if( model_id == product_availability[j][0] && product_availability[j][1] != 0 ) {
							if( (config_type == "condition_id" || current_selection_data[i][3] == 'auto') && product_availability[j][1] != 0 ) {
								product_availability[j][1] = -1;
							} else {
								product_availability[j][1] = 0;
							}
							number_available--;
						}
					}
				}
			}
		}
	}

	return all_selected;
}

var selected_child_class = "";

function update_product_information() {
	var i, j;

	all_selected = update_product_availability();

	// find the lowest & highest price out of currently available based on options
	lowest_price = -1;
	lowest_price_regular_price = 0;
	lowest_price_condition = '';
	lowest_price_num_available = 0;

	lowest_price_by_condition = new Object();

	highest_price = 0;
	show_child_id = 0;

	lowest_headcover_id = -1;

	for( i in product_availability ) {
		if( product_availability[i][1] == 0 ) {
			continue;
		}

		this_id = product_availability[i][0];
		this_available = product_availability[i][2];
		this_condition = product_availability[i][3];
		this_price = product_availability[i][4];
		this_regular_price = product_availability[i][5];
		this_headcover = product_availability[i][6];

		if( lowest_price_by_condition[this_condition] == undefined || this_price < lowest_price_by_condition[this_condition]) {
			lowest_price_by_condition[this_condition] = this_price;
		}

		if( product_availability[i][1] < 1 ) {
			continue;
		}

		if( lowest_price < 0 || this_price < lowest_price ) {
			lowest_price = this_price;
			lowest_price_regular_price = this_regular_price;
			lowest_price_condition = all_options["condition_id"][this_condition][2];
			lowest_price_num_available = this_available;
		}
		else if( this_price == lowest_price ) {
			lowest_price_num_available += this_available;
		}

		if( this_price > highest_price ) {
			highest_price = this_price;
			show_child_id = this_id;
		}

		if( lowest_headcover_id < 0 || this_headcover < lowest_headcover_id ) {
			lowest_headcover_id = this_headcover;
		}
	}

	// set lowest price & how many available at that price
	if( lowest_price > 0 && lowest_price_num_available && lowest_price_condition ) {
		$("#big-price").html(WGformatMoney(lowest_price));
		$("#regular-price-value").html(WGformatMoney(lowest_price_regular_price));
		$("#price-condition-name").html(lowest_price_condition);
		$("#only-x-left-value").html(lowest_price_num_available);

		$("#only-x-left").removeClass();
		$("#only-x-left").addClass("only-" + lowest_price_num_available + "-left");

		the_msrp = document.getElementById('hidden_msrp');
		if( the_msrp.value > 0 ) {
			lowest_price_savings = the_msrp.value - lowest_price;
			$("#you-save-dollar").html(WGformatMoney(lowest_price_savings));

			lowest_price_savings_percent = lowest_price_savings / the_msrp.value * 100.0;
			$("#you-save-percent").html(Math.round(lowest_price_savings_percent));
		}

		promotional_price = false;
		if( lowest_price < lowest_price_regular_price ) {
			promotional_price = true;
		}
		$("#regular-price").toggleClass("hide", !promotional_price);
	}

	// set headcover to lowest (is included -> not available -> not applicable)
	if( lowest_headcover_id > 0 && headcover_options.length > 0 ) {
		headcover_id = 'o' + lowest_headcover_id;
		var headcover_description='';
		for (j=0;j<headcover_options.length;j++) {
			if( headcover_id == headcover_options[j][0] ) {
				headcover_description = headcover_options[j][1];
				break;
			}
		}
		$("#search_headcover")[0].value= headcover_id;
		$("#headcover_description").html(headcover_description);
		$(".headcover-note .note").removeClass("Available").addClass(headcover_description);
	}

	// show condition when option selected
	for(i in current_selection_data) {
		if( current_selection_data[i][0] == 'condition_id' ) {
			if( current_selection_data[i][1] == 'none' || current_selection_data[i][1] == '' ) {
				selected_condition = 'none';
			} else {
				selected_condition = current_selection_data[i][1];
			}
			for( option in all_options["condition_id"] ) {
				$("#condition_" + option).toggleClass("hide", !(option == selected_condition));
			}

			$("#price-label-single").toggleClass("hide", (selected_condition == "none" || promotional_price));
			$("#price-label-multiple").toggleClass("hide", (selected_condition != "none" || promotional_price));
			$("#price-label-promo-single").toggleClass("hide", (selected_condition == "none" || !promotional_price));
			$("#price-label-promo-multiple").toggleClass("hide", (selected_condition != "none" || !promotional_price));
		}
	}

	// update condition pricing in options
	condition_options = $("#search_condition_id")[0].options;
	for( i=0; i<condition_options.length; i++ ) {
		key = condition_options[i].value;
		price = lowest_price_by_condition[key];
		if( price ) {
			condition_options[i].text += " (" + WGformatMoney(price) + ")";
		}
	}

	// show and hide child-specific data
	var selected_child_id = 0;

	// remove any child-specific class
	if( selected_child_class != '' ) {
		$("#pp-wrap").removeClass(selected_child_class);
		$("#pp-right-col").removeClass(selected_child_class);
		selected_child_class = '';
	}

	for( i in product_availability ) {
		model_id = product_availability[i][0];
		headcover_id = product_availability[i][6];

		// update product availability based on headcover
		if( headcover_id != lowest_headcover_id && product_availability[i][1] == 1 ) {
			product_availability[i][1] = 0;
		}

		// if all of the options are selected, there must be a child to match
		// select the first available one, which is stock before unique and oldest to newest
		if( all_selected && selected_child_id == 0 && product_availability[i][1] == 1 ) {
			selected_child_id = model_id;

			// append class of selected child
			if( product_availability[i][7] != '' ) {
				selected_child_class = product_availability[i][7];
				$("#pp-wrap").addClass(selected_child_class);
				$("#pp-right-col").addClass(selected_child_class);
			}
		}
	}

	if( selected_child_id > 0 ) {
		show_child_id = selected_child_id;
		$("#addtocart-active").addClass("child_set");
	}

	// show the SKU when set
	$("#hidden_product_id")[0].value = selected_child_id;
	$("#selected_child_id").html(selected_child_id);
	$("#pp-sku-id").toggleClass("hide", (selected_child_id == 0));

	// update child-specific information
	$.getJSON(
		"ajax_targets/get_child_product_settings.php",
		{child_id: show_child_id, selected: (selected_child_id>0)},
		function(j) { update_child_specific_product_information(j) }
	);
}

function update_child_specific_product_information( jresults ) {
	current_child_id = $("#current-child-id").html();
	new_child_id = jresults.id;

	images = jresults.images;

	if( images && images.length > 0 && current_child_id != new_child_id ) {
		// update main image and links to large image //
		large_image = images[0];
		regular_image = "http://www.3balls.com/scripts/timthumb.php?src=" + large_image + "&h=&w=240";
		switch_product_img(regular_image, large_image);

		// update representative/actual tag below image //
		if( jresults.actual_photo == "a" || jresults.actual_photo) {
			text = "Actual";
		} else {
			text = "Representative";
		}
		$("#rep-act-text").html(text);

		// update thumbnail images //
		thumbnail_image_html = "";
		if( images.length > 1 ) {
			$.each(jresults.images, function(key, image) {
				large_image = image;
				regular_image = "http://www.3balls.com/scripts/timthumb.php?src=" + large_image + "&h=&w=240";
				small_image = "http://www.3balls.com/scripts/timthumb.php?src=" + large_image + "&h=&w=58";

				list_element = '<li><a href="javascript:void(0)" onClick="switch_product_img(\'' + regular_image + '\', \'' + large_image + '\');"><img src="' + small_image + '" alt="" /></a></li>';
				thumbnail_image_html += list_element;
			});
		}
		$("#thumbs").html(thumbnail_image_html);
		$("#current-child-id").html(jresults.id)
	}

	// update highlights when child is selected //
	$(".highlight").toggleClass("hide", (!jresults.highlights && !jresults.specific_condition));
	if( jresults.specific_condition ) {
		$(".cond-description").html("<div class='note'>" + jresults.specific_condition + "</div>");
	} else {
		$(".cond-description").html("");
	}
	if( jresults.highlights ) {
		$(".highlight-description").html("<div class='note'>" + jresults.highlights + "</div>");
	} else {
		$(".highlight-description").html("");
	}
}

// Author   : Jonathan Weesner (http://cyberstation.net/~jweesner/)
// Copyright: Use freely. Keep Author and Copyright lines intact.					
var WGdc=".";
var WGgc=",";
var WGcs="$";
var WGnc="-";
function WGformatMoney(A) {
	var N=Math.abs(Math.round(A*100));
	var S=((N<10)?"00":((N<100)?"0":""))+N;
	S=WGcs+(A<0?WGnc:"")+WGgroup(S.substring(0,(S.length-2)))+WGdc+S.substring((S.length-2),S.length)+((A<0&&WGnc=="(")?")":"");
	return S;
}
// WGgroup inspired by Bill Dortch's usenet post (www.hidaho.com)
function WGgroup(S) {
	return (S.length<4)?S:(WGgroup(S.substring(0,S.length-3))+WGgc+S.substring(S.length-3,S.length));
}
			
function switch_product_img(regularImage, largeImage) {
	$("#photo img").attr("src", regularImage);
	$("#photo a").attr("href", largeImage);
	$("#zoom_link").attr("href", largeImage);
	$("#cart-pop img").attr("src", regularImage);
}

function validate_product_selection(the_form) {
	var initial_error_message = "Please select:\n";  
	var error_message = initial_error_message;  

	update_current_selections();

	// determine if all options are selected
	var all_selected = true;
	for(i in current_selection_data) {
		if( current_selection_data[i][1] == 'none' || current_selection_data[i][1] == '' ) {
			all_selected = false;
			error_message += "    " + current_selection_data[i][2] + "\n";
		}
	}

	// make sure the hidden product id has been set to the child
	var selected_child_id = $("#hidden_product_id")[0].value;
	if( all_selected == true && selected_child_id == 0 ) {
		error_message += "Invalid selections.\n";
	}

	if( error_message != initial_error_message ) {
		alert( error_message );
		return false;
	} else {
		return true;
	}
}

function debug(txt) {
	current_text = document.getElementById('debug_out').innerHTML;
	new_text = current_text + '<br/>' + txt;
	document.getElementById('debug_out').innerHTML = new_text;
}
function debug_reset() {
	document.getElementById('debug_out').innerHTML = '';
}


/*
 * tools.tabs 1.0.4 - Tabs done right.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/tabs.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : November 2008
 * Date: ${date}
 * Revision: ${revision} 
 */
(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery);


//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function($){$(document).ready(function(){$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom()});function format(str){for(var i=1;i<arguments.length;i++){str=str.replace('%'+(i-1),arguments[i])}return str}function CloudZoom(jWin,opts){var sImg=$('img',jWin);var img1;var img2;var zoomDiv=null;var $mouseTrap=null;var lens=null;var $tint=null;var softFocus=null;var $ie6Fix=null;var zoomImage;var controlTimer=0;var cw,ch;var destU=0;var destV=0;var currV=0;var currU=0;var filesLoaded=0;var mx,my;var ctx=this,zw;setTimeout(function(){if($mouseTrap===null){var w=jWin.width();jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>',w/3,(w/2)-(w/6))).find(':last').css('opacity',0.5)}},200);var ie6FixRemove=function(){if($ie6Fix!==null){$ie6Fix.remove();$ie6Fix=null}};this.removeBits=function(){if(lens){lens.remove();lens=null}if($tint){$tint.remove();$tint=null}if(softFocus){softFocus.remove();softFocus=null}ie6FixRemove();$('.cloud-zoom-loading',jWin.parent()).remove()};this.destroy=function(){jWin.data('zoom',null);if($mouseTrap){$mouseTrap.unbind();$mouseTrap.remove();$mouseTrap=null}if(zoomDiv){zoomDiv.remove();zoomDiv=null}this.removeBits()};this.fadedOut=function(){if(zoomDiv){zoomDiv.remove();zoomDiv=null}this.removeBits()};this.controlLoop=function(){if(lens){var x=(mx-sImg.offset().left-(cw*0.5))>>0;var y=(my-sImg.offset().top-(ch*0.5))>>0;if(x<0){x=0}else if(x>(sImg.outerWidth()-cw)){x=(sImg.outerWidth()-cw)}if(y<0){y=0}else if(y>(sImg.outerHeight()-ch)){y=(sImg.outerHeight()-ch)}lens.css({left:x,top:y});lens.css('background-position',(-x)+'px '+(-y)+'px');destU=(((x)/sImg.outerWidth())*zoomImage.width)>>0;destV=(((y)/sImg.outerHeight())*zoomImage.height)>>0;currU+=(destU-currU)/opts.smoothMove;currV+=(destV-currV)/opts.smoothMove;zoomDiv.css('background-position',(-(currU>>0)+'px ')+(-(currV>>0)+'px'))}controlTimer=setTimeout(function(){ctx.controlLoop()},30)};this.init2=function(img,id){filesLoaded++;if(id===1){zoomImage=img}if(filesLoaded===2){this.init()}};this.init=function(){$('.cloud-zoom-loading',jWin.parent()).remove();$mouseTrap=jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:999;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;\'></div>",sImg.outerWidth(),sImg.outerHeight(),0,0)).find(':last');$mouseTrap.bind('mousemove',this,function(event){mx=event.pageX;my=event.pageY});$mouseTrap.bind('mouseleave',this,function(event){clearTimeout(controlTimer);if(lens){lens.fadeOut(299)}if($tint){$tint.fadeOut(299)}if(softFocus){softFocus.fadeOut(299)}zoomDiv.fadeOut(300,function(){ctx.fadedOut()});return false});$mouseTrap.bind('mouseenter',this,function(event){mx=event.pageX;my=event.pageY;zw=event.data;if(zoomDiv){zoomDiv.stop(true,false);zoomDiv.remove()}var xPos=opts.adjustX,yPos=opts.adjustY;var siw=sImg.outerWidth();var sih=sImg.outerHeight();var w=opts.zoomWidth;var h=opts.zoomHeight;if(opts.zoomWidth=='auto'){w=siw}if(opts.zoomHeight=='auto'){h=sih}var appendTo=jWin.parent();switch(opts.position){case'top':yPos-=h;break;case'right':xPos+=siw;break;case'bottom':yPos+=sih;break;case'left':xPos-=w;break;case'inside':w=siw;h=sih;break;default:appendTo=$('#'+opts.position);if(!appendTo.length){appendTo=jWin;xPos+=siw;yPos+=sih}else{w=appendTo.innerWidth();h=appendTo.innerHeight()}}zoomDiv=appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:99;"></div>',xPos,yPos,w,h,zoomImage.src)).find(':last');if(sImg.attr('title')&&opts.showTitle){zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>',sImg.attr('title'))).find(':last').css('opacity',opts.titleOpacity)}if($.browser.msie&&$.browser.version<7){$ie6Fix=$('<iframe frameborder="0" src="#"></iframe>').css({position:"absolute",left:xPos,top:yPos,zIndex:99,width:w,height:h}).insertBefore(zoomDiv)}zoomDiv.fadeIn(500);if(lens){lens.remove();lens=null}cw=(sImg.outerWidth()/zoomImage.width)*zoomDiv.width();ch=(sImg.outerHeight()/zoomImage.height)*zoomDiv.height();lens=jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:98;position:absolute;width:%0px;height:%1px;'></div>",cw,ch)).find(':last');$mouseTrap.css('cursor',lens.css('cursor'));var noTrans=false;if(opts.tint){lens.css('background','url("'+sImg.attr('src')+'")');$tint=jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />',sImg.outerWidth(),sImg.outerHeight(),opts.tint)).find(':last');$tint.css('opacity',opts.tintOpacity);noTrans=true;$tint.fadeIn(500)}if(opts.softFocus){lens.css('background','url("'+sImg.attr('src')+'")');softFocus=jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />',sImg.outerWidth()-2,sImg.outerHeight()-2,opts.tint)).find(':last');softFocus.css('background','url("'+sImg.attr('src')+'")');softFocus.css('opacity',0.5);noTrans=true;softFocus.fadeIn(500)}if(!noTrans){lens.css('opacity',opts.lensOpacity)}if(opts.position!=='inside'){lens.fadeIn(500)}zw.controlLoop();return})};img1=new Image();$(img1).load(function(){ctx.init2(this,0)});img1.src=sImg.attr('src');img2=new Image();$(img2).load(function(){ctx.init2(this,1)});img2.src=jWin.attr('href')}$.fn.CloudZoom=function(options){try{document.execCommand("BackgroundImageCache",false,true)}catch(e){}this.each(function(){var relOpts,opts;eval('var	a = {'+$(this).attr('rel')+'}');relOpts=a;if($(this).is('.cloud-zoom')){$(this).css({'position':'relative','display':'block'});$('img',$(this)).css({'display':'block'});if($(this).parent().attr('id')!='wrap'){$(this).wrap('<div id="wrap" style="top:0px;z-index:9999;position:relative;"></div>')}opts=$.extend({},$.fn.CloudZoom.defaults,options);opts=$.extend({},opts,relOpts);$(this).data('zoom',new CloudZoom($(this),opts))}else if($(this).is('.cloud-zoom-gallery')){opts=$.extend({},relOpts,options);$(this).data('relOpts',opts);$(this).bind('click',$(this),function(event){var data=event.data.data('relOpts');$('#'+data.useZoom).data('zoom').destroy();$('#'+data.useZoom).attr('href',event.data.attr('href'));$('#'+data.useZoom+' img').attr('src',event.data.data('relOpts').smallImage);$('#'+event.data.data('relOpts').useZoom).CloudZoom();return false})}});return this};$.fn.CloudZoom.defaults={zoomWidth:'auto',zoomHeight:'auto',position:'right',tint:false,tintOpacity:0.5,lensOpacity:0.5,softFocus:false,smoothMove:3,showTitle:true,titleOpacity:0.5,adjustX:0,adjustY:0}})(jQuery);

