$(document).ready(function() {

//Make sure to only run this script once for a given page (views admin page esp. was running it MANY times)
if(!$('body').hasClass('funcs-run')) {
	$('body').addClass('funcs-run');



//--- Makes seperate lines of links function as one

$('.view-id-uc_products .views-row').bind('mouseenter mouseleave', function() {
	$(this).toggleClass('hover');
});
$('.cart-related-item').bind('mouseenter mouseleave', function() {
	$(this).toggleClass('hover');
});
$('.upsell-block-product').bind('mouseenter mouseleave', function() {
	$(this).toggleClass('hover');
});

$('form#jump-custom-quickly-form-1 #edit-submit').hide();
$('form#jump-custom-quickly-form-1 .form-select').change(function() {
	$('form#jump-custom-quickly-form-1').submit();
});


// --- Moves the Service Links up to the Pinterest block

	$('.service-links').prependTo('#block-views-pinterest_link-block_1');


// ---  Start Input Box Interactivity   

	$('.front #wpopup-address').val('Your e-mail address goes here');
	$('.front #wpopup-address').focus(function () {
		if($(this).val() == 'Your e-mail address goes here') {
			$(this).val('').addClass('filled');
		}
	});
	$('.front #wpopup-address').blur(function () {
		if($(this).val() == '') {
			$(this).val('Your e-mail address goes here').removeClass('filled');
		}
	});

//---Add a label on the product image
	$('<div class="product-image-label">Click for larger image.<\/div>').appendTo('.main-product-image .lightbox-processed');
//	var productPrice = $('.product-info').remove();
//	productPrice.prependTo('.more-product-images');


//---Add some formatting to the Cart Links

	if(!$('#block-uc_cart-0').hasClass('wrapped')) {
		$('#block-uc_cart-0 .num-items').prepend('<span class="teal">cart:</span>(').append(')');
		$('#block-uc_cart-0 .cart-block-summary-items').wrapInner('<a href="/cart" class="cart" />');
		$('#block-uc_cart-0').addClass('wrapped');
	}

// --- Add some rounded corners

	$('.block-jump_custom .title').corner("round 6px");
	$('#block-block-14').corner("round 6px");
	$('#block-block-15 .form-text').corner("round 3px");
	$('.field-changer .field-item').corner("round 4px");

//---Append/Prepend/Wrap some things

	$('.block-jump_custom .block-inner').prepend('<div class="language-earth"></div>');
	$('.front h1.title').wrapInner('<span class="title-text">');
	$('.front h1.title').prepend('<span class="title-prefix"></span>');
	$('.front h1.title').append('<span class="title-suffix"></span>');
	$('#block-uc_upsell-0 h2').append('<br/><span class="sub-title">with these....</span>');
	if($('.add-to-cart').length > 0) {
		$('body').addClass('product-item');
	}
	if($('.webform-confirmation').length > 0) {
		$('body').addClass('node-type-page');
	}


//--- Input box interactivity

	$('.front #edit-submitted-your-email-address').each(function() {
			var default_value = this.value;
			$(this).focus(function() {
					if(this.value == default_value) {
							this.value = '';
					}
			});
			$(this).blur(function() {
					if(this.value == '') {
							this.value = default_value;
					}
			});
	});


/* drive .item-list active state from header link (cid2011.css HERK-060211) */
$('.view-product-nav .item-list h3 a.active').parent().parent().addClass("active");

//--- Standard Product Display


	$('.view-std-products .field-image .field-item').each(function() {
		$(this).addClass('hide');
	});
	$('.view-std-products .field-image .field-item:first-child').each(function() {
		$(this).removeClass('hide');
	});

	$('.view-std-products .field-changer').each(function() {
		$(this).addClass('hide transparent');
	});

	$('.view-std-products .field-changer .field-item').parent().each(function() {
		$(this).removeClass('hide transparent');
	});

	$('.view-std-products .field-changer .field-item:first-child').addClass('active');

	$('.view-std-products .field-changer .field-item').each(function() {
		$(this).wrapInner('<div class="transparent">');
	});

	$('.view-std-products .field-changer .field-item').mouseover(function() {
		showimg=$(this).text();

		$(this).parent().find('.field-item').each(function() {
			$(this).removeClass('active');
		});

		$(this).addClass('active');

		$(this).parent().parent().find('.field-image .field-item').each(function() {
			$(this).addClass('hide');

			if($(this).find('img.imagecache').attr('src') == showimg) {
				$(this).removeClass('hide');
			}

		});

	});


//--- Product Node Image Display

	$('.view-product-images .field-image .field-item').each(function() {
		$(this).addClass('hide');
	});
	$('.view-product-images .field-image .field-item:first-child').each(function() {
		$(this).removeClass('hide');
	});
	$('.view-product-images .field-thumbs .field-item').each(function() {
		$(this).addClass('shrink');
	});
	$('.view-product-images .field-thumbs>img').parent().addClass('shrink');


	$('.view-product-images .field-thumbs .field-item').mouseover(function() {
		showimg=$(this).find('img.imagecache').attr('src')

		$(this).parent().find('.field-item').each(function() {
			$(this).removeClass('active');
		});

		$(this).addClass('active');

		$(this).parent().parent().find('.field-image .field-item').each(function() {
			$(this).addClass('hide');

			if($(this).find('img.imagecache').attr('src') == showimg) {
				$(this).removeClass('hide');
			}

		});

	});

//--- Grabs email address for the popup webform

	var wpopup_address;

	$('#wpopup-address').blur(function() {
		wpopup_address = $('#wpopup-address').val();
	});

	$('#modalContainer:not(.action-bound)').bind('mouseenter', function() {
		$('#edit-submitted-e-mail').val(wpopup_address);
		$('#modalContainer').addClass('action-bound');
	});



//--- Adds the .active class up all levels --  use when page loads

	$('.active').parents('.menuparent').children('a').addClass('active');


//--- Helps to style and manage the drop-downs

	if($('.language-select').length > 0) {
		$('body').addClass('has-language-selector');
	}
		$('#edit-jump-custom-goto').prepend('<option selected value="">Select a Language</option>');

	$('#content').find('.language-select').each(function() {
			$(this).prepend('<option selected value="">Select a Language</option>');
	});

	views_group_by_field('.view-std-products', '.views-group', '.language');
	views_group_jump_by_field('.view-std-products', '.language');

}});


//Group a view by an arbitrary field (the fieldSelector must point to a PLAIN TEXT FIELD that can be easily converted to a CSS class)
// PLEASE NOTE that the the Selector arguments are CSS SELECTORS (start them with a . or #)
// If a candidate row DOES NOT MATCH the languageFieldSelector, it WILL NOT be added to the group, because grouping is
//   done specifically to support rows with languages
function views_group_by_field(viewSelector, groupFieldSelector, languageFieldSelector) {
	var previousGroupClass = '';  //This represents the previous group matched in the loop below - if this is different from the current group class,
																// we'll be adding a termgroup-last class to the previous record and a termgroup-first to the current item.
																// We also wrap up all the grouped rows in a group-wrapper div.
	var previousRowObj = '';      //This is the views row from the previous loop
	var rowGroupObj = '';         //This represents the object in each views row containing a string that we can group by

	//Loop through each views row
	$(viewSelector+' .views-row').each(function() {
		// Process Taxonomy term groups
		// $(this) represents the current views-row we're looping through
		rowGroupObj = $(this).find(groupFieldSelector);
		rowLangObj = $(this).find(languageFieldSelector);
		if(rowGroupObj.html().length > 0 && rowLangObj.length > 0) {
			groupClass = classifize(rowGroupObj.html());  //groupClass is a valid CSS class name string to be added to the group DIVs
			$(this).addClass('group-name-'+groupClass);

			if(previousGroupClass != groupClass) {     //We've encountered a views row in a new group!
				$(this).addClass('group-first');         //Add a class to identify the first row in the group
				if(previousGroupClass.length>0) {        //If this is not the first group in the list...
					previousRowObj.addClass('group-last'); // add a class to the last row in the previous group and then wrap up the group in a wrapper
					$(viewSelector+' .group-name-'+previousGroupClass).wrapAll('<div id="group-'+previousGroupClass+'" class="group-wrapper wrap-'+previousGroupClass+'" />');
				}
			}
			//Save previous row data for use later on in the loop
			previousGroupClass = groupClass;
			previousRowObj = $(this);
		}
	});
	//This adds the group-last class and wraps up the LAST group encountered.  The loop above won't catch the last group.
	if(previousRowObj.length>0) {
		previousRowObj.addClass('group-last')
		$(viewSelector+' .group-name-'+previousGroupClass).wrapAll('<div id="group-'+previousGroupClass+'" class="group-wrapper wrap-'+previousGroupClass+'" />');
	}
}

function classifize(str) {
	return str.replace(/ /g,'-').replace(/[!:]/g,'');
}

function views_group_jump_by_field(viewSelector, languageFieldSelector) {
	//Loop through each group within the view
	$(viewSelector+' .group-wrapper').each(function() {
		if($(this).find('.views-row').length>1) {
			var languages = new Array();
			$(this).find('.views-row').each(function() {
				rowLanguageObj = $(this).find(languageFieldSelector);
				if(rowLanguageObj.length > 0 && rowLanguageObj.html().length > 0) {
					languageClass = classifize(rowLanguageObj.html());  //languageClass is a valid CSS class name string to be added to the views row
					$(this).addClass('language').addClass('language-name-'+languageClass);
					languages.push(rowLanguageObj.html());
				}
			});
			if(languages.length > 0) {
				selectCode='<select onchange="views_group_jump_change(this);" class="language-select" id="language-select-'+$(this).attr('id')+'">';
				for(a=0;a<languages.length;a++) {
					languageClass = classifize(languages[a]);
					selectCode += '<option value="'+languageClass+'">'+languages[a]+'</option>';
				}
				selectCode += '</select>';
				$(this).prepend(selectCode);
			}
		}
	});
}

function views_group_jump_change(selectObj) {
	selectedValue = $(selectObj).val();
	$(selectObj).parent().find('.views-row').hide();
	$(selectObj).parent().find('.language-name-'+selectedValue).show();
}

function replaceAll(txt, replace, with_this) {
  return txt.replace(new RegExp(replace, 'g'),with_this);
}


/**
	-------------- AUTO SKU -------------
	ALLOWS USER TO EASILY AUTO-POPULATE
	ADJUSTMENT SKUS FROM ATTRIBUTES
*/
Drupal.behaviors.autoSKU = function(){
    //if we're on the product adjustments page, add a button to automatically set sku's
    if($('#uc-product-adjustments-form').length > 0){

				//Using before(), these will appear in reverse order of how they're coded here
        $('#uc-product-adjustments-form').before($('<a class="auto_sku_options">Automatically set SKU using Color and Size\'s</a><br/>').css('cursor', 'pointer').click( function() {
					autosku_color_size();
        }));
//ADD NEW ACTION LINKS HERE
//        $('#uc-product-adjustments-form').before($('<a class="auto_sku_options">Automatically set SKU using Color and Size\'s</a><br/>').css('cursor', 'pointer').click( function() {
//					autosku_some_other_format();
//        }));
    }
}

//-------- AUTOSKU ACTION FUNCTIONS ----------
function autosku_color_size() {
	base = autosku_base(); rows = autosku_rows(); rows.each(function(){ attrs = autosku_attrs($(this));

	//Build SKU here
	val = base
		+ autosku_format_color(attrs[0])
		+ autosku_format_size(attrs[1]);

	autosku_set($(this), val); });
}
// function autosku_some_other_format() {
// 	base = autosku_base(); rows = autosku_rows(); rows.each(function(){ attrs = autosku_attrs($(this));
// 	//Build SKU here
// 	val = base
// 		+ autosku_colorcode(attrs[0])
// 		+ attrs[1];

// 	autosku_set($(this), val); });
// }

//-------- AUTOSKU FORMATTER FUNCTIONS ----------
function autosku_format_size(size) {
	size = size.replace('x','');
	return size;
}
function autosku_format_color(color) {
	color = color.replace(' ','');
	//Add color replacement options here - key is the color name WITH NO SPACES
	var colors = {
		Beige: 'bei',
		Blue: 'blu',
		Brown: 'dgr',
		Grey: 'lgr',
		Pink: 'red'
	}
	code = colors[color];
	if(!code) code = color.toLowerCase().substr(0, 3); //Use first three characters if not in link table
	return code;
}

//-------- AUTOSKU HELPER FUNCTIONS ----------
//Returns the base sku
function autosku_base() {
	base = $('#uc-product-adjustments-form').find('b:contains(\'Default product SKU:\')').html().split(':');
	base = trimit(base[1]);
	return base;
}
//Returns the tr rows for each adjustment
function autosku_rows() {
	return $('#uc-product-adjustments-form .combinations tbody tr');
}
//Pass this the sku adjustment tr/row object, returns an array of attributes
function autosku_attrs(obj) {
	attrs = new Array();
	n=0;
	obj.find('td').each(function() {
		if($(this).find('div').length>0) return; //skip cells with anything other than plain text
		attrs[n] = trimit($(this).html());
		n++;
	});
	return attrs;
}
//Sets the attribute value
function autosku_set(obj, val) {
	val = val.replace(' ','');
	obj.find('.form-text').val(val);
}
/* trim12() from http://blog.stevenlevithan.com/archives/faster-trim-javascript */
function trimit (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}
/** -------------- END AUTO SKU ------------- */

