var global_Current_ProductCode = "";

/*************************************/
function params(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/*************************************/
function loadStylesheet(e) {
  return $('head').append('<link rel="stylesheet" href="'+e+'" type="text/css" />');
}

/*************************************/
function trim(s)
{
    var l=0; var r=s.length -1;
    while(l < s.length && s[l] == ' ')
    {     l++; }
    while(r > l && s[r] == ' ')
    {     r-=1;     }
    return s.substring(l, r+1);
} 

/*************************************/

function AddClassIDs(){
	//Add class names 

	//For Catagory View Page
	var productsRowTbody = $(".productnamecolor").parent().parent().parent();
	$(productsRowTbody).addClass("productsRowTbody");
	var productsRowTable = $(productsRowTbody).parent();
	$(productsRowTable).addClass("productsRowTable");
	$(productsRowTable).parent().addClass('productRowContainer');
	$('.productRowContainer').parent().parent().parent().addClass('ProductRows'); 
	$('.productRowContainer').parent().parent().parent().attr('id','ProductRows');
	$('.ProductRows').parent().parent().parent().parent().attr('id','ProductsContainterTable');
	
	$('.PageText_L517n').parent().parent().parent().parent().parent().parent().attr('id','PageBC');
	$('#jmenuhide').parent().parent().parent().parent().parent().parent().parent().parent().attr('id','PageNaviRow');
	
	//Add ID to Product Detail Area
	$('#product_photo_zoom_url').parent().parent().parent().parent().parent().attr('id', 'ProductPhotoArea'); //Append Choose your container here.
	$('#ProductPhotoArea').parent().attr('id','ProductDetailArea');
	$('#product_photo_zoom_url').parent().attr('id', 'ProductLinks');

	//Add ID to Description area
	$('.colors_pricebox').parent().attr('id', 'ProductDescriptionArea');

	//Create ID's	
	$('.productNameInDescription').parent().addClass('DescArea');
	$('.DescArea').parent().parent().parent().attr('id','DescAreaParentTable');

	$('.wishpot_form').parent().attr('id','addlButtons');
	$('.wishpot_form').remove();
	$('#addlButtons').parent().parent().parent().attr('id','OptionsArea');
	$('#OptionsArea').parent().attr('id','OptionsParentContainer');
	$('#OptionsParentContainer table:nth-child(1)').attr('id', 'OptionDropDown');
	$('#OptionDropDown').addClass('OptTitle');
	$('#OptionDropDown td:nth-child(1)').attr('id','OptTitle');
	$('#OptTitle').parent().children().addClass('OptionsTDs');


	//ID Related Products Table
	$('.PageText_L666n').parent().parent().parent().parent().parent().parent().attr('id','RelatedProductTable');
	$('#RelatedProductTable').parent().parent().parent().parent().attr('id','RelatedProductTableParent');
	
	//Put elements in new Div Areas
	//Put the price area in a div.
	$('.PageText_L483n').parent().parent().wrap("<div class='ProductPriceText' />");
	// Put the Product Code stuff in a div.
	$('.product_code_title').parent().parent().wrap("<div id='ProductCodeText' class='ProductCodeText' />");	
	$('#RelatedProductTableParent').parent().parent().parent().parent().attr('id','ExtendedInfoParentTable');
	
	
	//If there is data in the product description. Look for locator div.
	$('.PageText_L656n').parent().parent().parent().parent().parent().parent().parent().attr('id','ExtendedInfoTable');	
		

	//Related Products area
	$('.PageText_L665n').parent().parent().parent().parent().parent().parent().attr('id','RelatedProductsTable');
	$('#RelatedProductsTable').addClass('RelatedProductsTable');
}

/*************************************/

function ReBuildProductsTable(){
	var ProdRow = [];
	ProdRow['Empty']=1;
	ProdRow['Img']=1;
	ProdRow['Data']=1;
	
	$('.productsRowTbody > tr').each( function(row,element){	
		switch( $(this).children().children().size() ){
			case 0:
				$(this).addClass('EmptyRow'+ProdRow['Empty']);
				$('.EmptyRow'+ProdRow['Empty']).children().each( function(index,element){
					$(this).attr('id','EmptyRow_'+ProdRow['Empty']+"_"+ (index+1));
				});
				ProdRow['Empty']++;
				break;
			
			case 2:
			case 4:
				$(this).addClass('ImgRow'+ProdRow['Img']);
				$('.ImgRow'+ProdRow['Img']).children().each( function(index,element){
					$(this).attr('id','ImgRow_'+ProdRow['Img']+"_"+ (index+1));
				});
				ProdRow['Img']++;
				break;
				
			case 3:
			case 6:
			case 9:
			case 12:
				$(this).addClass('DataRow'+ProdRow['Data']);
				var DataCount=1;
				$('.DataRow'+ProdRow['Data']).children().each( function(index,element){
					if($(this).html()!=""){
						$(this).attr('id','DataRow_'+ProdRow['Data']+"_"+ DataCount);
						DataCount++;
					}
				});
				ProdRow['Data']++;
				break;
				
			default:
				//alert( "Category difference" );
				//$(this).css('display','none');
		
		}
	});


	//Rearrange Data and Images to my design
	for(var x=1; x<=(ProdRow['Img']-1); x++){
		$('.ImgRow'+x).children().each( function(index,element){
			var Pricing = $('#DataRow_'+x+'_'+ (index+1)).html();
			if(Pricing == null || Pricing=='null') Pricing = "";
			var PrevContent = "<div class='ProductPhoto'>" + $(this).html() + "</div>";
			var newContent = "<div class='ProductDesc'>" + Pricing + "</div>" + PrevContent;		
			$(this).html(newContent);
			$(this).addClass('ProductTD');
			
			$('#DataRow_'+x+'_'+ (index+1)).css('display','none');
		});
	}
				
	//Remove border from product images
	$('.ProductPhoto img').each( function(index,element){
		$(this).addClass("ImgProductPhoto");
		$(this).css('border', 'none'); 
		$(this).attr('width', '194');
	});

}

/*************************************/
function AdjustFeatureButtons(){
	
	//FeatureButtons - Category Banner
	$('#feature_buttons').parent().parent().parent().parent().attr('id', 'CatBanner');
	$('#CatBanner').attr('cellspacing', '0');
	$('#CatBanner').attr('cellpadding', '0'); 

	//Adjust Table spacing for Banners below Products on Catagory page.
	$('#feature_buttons2').parent().parent().parent().parent().attr('id','LowerBanners');
	$('#LowerBanners').attr('cellspacing', '0');
	$('#LowerBanners').attr('cellpadding', '0'); 
}

/*************************************/
function FixBreadcrumb(){

	//BreadCrumb Changes
	//Breadcrumb_text bc_style
	var bcText = $('.PageText_L517n').parent().html();
	$('#Breadcrumb_text').html(bcText);
	$('#PageBC').html( $('#bc_style').html() );
	
	//Product Page ---------------------------------
	//Breadcrumb Product name
	$('.productnamecolorLARGE').parent().attr('id','PageBC');
	$('#PageBC > img').remove();
	$('#PageBC > br').remove();
	var bcText = $('#PageBC').html();
	$('#Breadcrumb_text').html(bcText);
	$('#PageBC').html( $('#bc_style').html() );

}

/*************************************/
function StyleSimilarCatagories(){
	//Title of section, add id to table.
	$('.PageText_L492n').parent().parent().parent().parent().parent().attr('id','SimilarCategoriesTable');
	$('#SimilarCategoriesTable').addClass('colors_backgroundlight');
	$('#SimilarCategoriesTable > td').addClass('SimilarCats');
	$('#SimilarCategoriesTable').insertBefore( $('#social') );		
}

/*************************************/
function MoveExtendedDescription(){
	
	//Move Additional Descriptions, Technical, Features and Extended Info into Top Scroller
	//ID Description and Related product table.  Relocate needed info.
	
	if( $('#ExtendedInfoTable').html() != 'null' ){
		$('#ExtendedInfoTable').hide(); 
		//ExtProductFields Get Eextended Field Data
		$('#DescParent').append( "<br clear='all' /><div id='ExtProductFields' style='display:none;'><b>Extended Information</b><br></div>" );
		var ExtInfo = $('#ProductDescription').parent().html();
		if(ExtInfo != null){
			$('#ExtProductFields').append( ExtInfo + '<br />');
			if( ExtInfo.length > 100 ) $('#ExtProductFields').show();
		}
	}
}

/*************************************/
function ProductReviews(){
	
	//Product has no review yet.
	if( $('.PageText_L493n').html() != 'null' ){
		$('.PageText_L493n').wrap("<div id='ProductReview'  />");
	} 
	
	//Product has a review.	
	if( $('.PageText_L509n').html() != 'null' ){
		$('.PageText_L509n').wrap("<div id='ProductReview'  />");
	} 
}

/*************************************/
function RelatedProductsSection(){
	
	//Add the New Related Product Area imidiatly after the form which encompases the product area.
	$("<div id='NewRelatedProductsArea'></div>").insertAfter('form[name="MainForm"]');
	$('#NewRelatedProductsTable').appendTo('#NewRelatedProductsArea');
	
	if( $('#NewRelatedProductsArea').html() != 'null' ) {
		var RelatedProducts = Array;
		var RelatedCount=0;
		$('#RelatedProductTable > tbody > tr > td > table > tbody > tr > td > a > img').each( function(index,element){
				RelatedProducts[index] = $(this).parent().parent().html();
				RelatedCount++;
		});

		$('#NewRelatedProductsTable').attr('cellspacing','2');
		//Drop the old Prod images in the New Area
		
		$('.NewRelProdImg').each( function(index,element){ $(this).append(RelatedProducts[index]); })
		//Update the image attribute to the necessary image size.
		
		$('.NewRelProdImg > a > img').attr('width','190');
		
		//Hide old Related Products Table.
		$('#RelatedProductTableParent').remove();
		
		//Hide New Related Products if it's less then 3 items...
		if(RelatedCount < 3) $('#NewRelatedProductsArea').css('display','none');

	}
	
}

/*************************************/
function FixPagingBar(){
	
	//Category Page - Fix next page img
	var NextPageBtn = $('.next_page_img').parent().parent().html();
	
	$('#PageNaviRow tr:nth-child(2)').remove();
	$('#PageNaviRow > tr').append(NextPageBtn);
	
	//Encapsulate Pageing bar, wrap in div.
	//Add id to Sort/Pagination table
	$('#PageNaviRow').parent().attr('id','SortPageTable');
	 
	//Wrap page/sorting code in a DIV
	$('#SortPageTable').wrap("<div id='SortPageDiv' class='SortPageDivClass' />");
	$('.next_page_img').parent().attr('align',"right");
	
}
/*************************************/
function AdjustPage(){

	//For this page 'any' add appropriate class and id's
	AddClassIDs();

	//Global style changes
	$('table').attr('cellpadding', '0');
	$('table').attr('cellspacing', '0');

	//Remove content_area div root breaks.
	$('#content_area > br').remove();
	$('.DescArea > br').remove();
	$('.PageText_L668n').remove();


	
	//*********************************
	//Catagory Page Changes
	//*********************************
	$('.productsRowTable').attr('cellspacing', '2');
	
	//Remove Unused areas
	$('td[background*="/v/vspfiles/templates/yum/images/Grid_Divider_Vertical.gif"]').replaceWith('');
	$('td[background*="/v/vspfiles/templates/yum/images/Grid_Divider_Horizontal.gif"]').parent().replaceWith('');

	FixPagingBar();
	FixBreadcrumb();
	AdjustFeatureButtons();
	ReBuildProductsTable();


	//*********************************
	//Product Detail Page Changes
	//*********************************
	
	//Encapsulate ProductDetail area in new table
	var OldProductDetailArea = $('#ProductDetailArea').html();
	$('#ProductDetailArea').html('<td colspan=2><table id="ProductDetailTable"><tr>' + OldProductDetailArea + '</tr></table></td>');

	var DescInfo = $('.DescArea').html();
	$('.DescArea').html( "<div id='DescParent' class='DescParent'>" + DescInfo + "</div>");

	//Option Name
	var OptionName = $("input[name='SELECT___CANDY-001___54']").attr('name');
	//Encapulate the Alternate View Photo's into Div's and move to Description Area.
	var OptionsSpec = $('.OptionSpecTemplate').attr('rel');
	if(!OptionsSpec && $('.OptionsTDs > input').attr('type')!='image'){  OptionsSpec='GenericOptions'; }

	var AddToCartBtn = $("input[name='btnaddtocart']").parent().html();
	var WishListBtn = $("input[name='btnaddtowishlist']").parent().html();
	//var Registry = $('.wishpot_form').html();

	switch(OptionsSpec){
		
		case "CandyContainer":
			//Move Buttons from Under Image.
			$('#ProductLinks > a').each( function(index,element){  $(this).attr("id","LinkEl" + index );    });
			$('#LinkEl1').remove();
			$('#LinkEl2').wrapAll('<div id="EmailFriend" />');
			var FriendButton = $('#EmailFriend').html();
			$('#EmailFriend').remove();
			//$('<div id="EmailButton">' + FriendButton + '</div>').insertBefore('.wishpot_form');
			$("<td></td>").insertBefore('#addlButtons');
			//Remove breaks from below Image.
			$('#ProductLinks > br').remove();

			//Deal with Alternate View Photos
			$('#DescParent').append('<div id="AlternatePhotoParent" style="display:none;"></div>');
			$('#AlternatePhotoParent').html("<font class='AltPhotoText'>Alternate Photos:</font><br>");
			$('#alternate_product_photo_2').parent().wrapAll('<div id="AltPhoto2" class="AltPhotos" />');
			$('#alternate_product_photo_3').parent().wrapAll('<div id="AltPhoto3" class="AltPhotos" />');
			$('#alternate_product_photo_4').parent().wrapAll('<div id="AltPhoto4" class="AltPhotos" />');
			if( $('.AltPhotos').html() != 'null' ) {
				var AllAltPhotos = $('.AltPhotos').html();
				$('.AltPhotos').remove();
				$('#ProductPhotoArea > br').remove();
				$(AllAltPhotos).appendTo('#AlternatePhotoParent');	 
			}
			if( $('#AltPhoto2').html() != null ) $('#AlternatePhotoParent').show();

			$('#ProductPhotoArea').append("<div id='ContainersDiv'></div>"); 
			break;
		
		
		
		case "GenericOptions":
			//Move Product Options if they exist to DescArea, below Product Code, above Ext Info.
			$('#OptionDropDown').wrap("<div id='GenericOptions' />");
			var ProdOptions = $('#GenericOptions').html();
			$('#GenericOptions').remove();
			$("<!--<br /><span class='OptionsTitle'>Product Options:</span>-->" + ProdOptions).insertAfter('#ProductCodeText');
			$('#OptionsParentContainer > br').remove();
			$('#ProductDescriptionArea > br').remove();

			//Identify parent table and remove it.
			var ActionButtons= $('#OptionsParentContainer').html();
			$('#OptionsParentContainer').parent().parent().parent().attr('id','OldOptionsTable');
			$('#OldOptionsTable').parent().parent().parent().parent().attr('id','OldOptionsContainerTable');
			$('#OldOptionsContainerTable').parent().parent().parent().parent().attr('id','OldOptionsContainerTable2');
			$('#OldOptionsContainerTable2').remove();
			$('#ProductDescriptionArea').append(ActionButtons); 
			//$('#ProductDescriptionArea').parent().attr('id','ProductDetailTR');
			//var OldProductDetailArea = $('#ProductDetailTR').html();
			//$('#ProductDetailTR').html('<td colspan=2><table id="ProductDetailTable"><tr>' + OldProductDetailArea + '</tr></table></td>');
			break;
		
		//Default view with or without options.
		default:
			//Move Cart Buttons out of DescArea		
			$('.DescArea').attr('colspan','2');
			$('.DescArea').css('height','385px');
			
			$('#OptionsParentContainer').css('display','none');
			$('#ProductDescriptionArea').append("<table align='center' valign='middle' width='100%' cellpadding='2' cellspacing='2' id='CartButtons'><tr><td >"+AddToCartBtn+"</td><td ></td></tr><tr><td height='25'>"+WishListBtn+"</td><td height='25'><div id='RegistryButton' style='padding-top:3px'>"+Registry+"</div></td></tr></table>");
			break;
		
	}	
  	
	ChangeProductPhoto();
	ProductReviews();
  
	if( $('.PageText_L155n').html() != 'null' ) AdjustHomePage();
	if( $('.PageText_L656n').html() != 'null' ) MoveExtendedDescription();
	
	if( $('.PageText_L666n').html() != 'null' ) RelatedProductsSection();
	
	if( $('.PageText_L492n').html() != 'null' ) StyleSimilarCatagories();

	//Show the Content area after I've made all these changes.
	$('#content_area').show('slow', function(){
											 
		$('#nav').fadeIn('slow');
	});
	
}
/*************************************/
function ChangeProductPhoto(){
/*
	var path = "/v/vspfiles/photos/";
	if(global_Current_ProductCode){
		var BetterImage = path + global_Current_ProductCode + ".png";
		var OldFile = $('#product_photo').attr('src');
		$('#product_photo').attr('rel',OldFile);
		
		//Add on error event in case png doesn't exit.
		$('#product_photo').error(function() {
			$('#product_photo').attr('src', $('#product_photo').attr('rel') );
		});
	
		$('#product_photo').attr('rel',OldFile);
		$('#product_photo').attr('width','328');
		$('#product_photo').attr('height','328');
		$('#product_photo').attr('src',BetterImage);
	}
*/
}

/*************************************/
function AdjustHomePage(){
	
	$('.PageText_L155n').parent().attr('id','HomeTableLayout');
	$('#HomeTableLayout > br').remove();
	
}
/*************************************/
function buildIDTree(parent, root, key1, key2){
	//Check that is valid element
	if( $(parent) ) {
		//Step through this element set and name each one by element type.
		$(parent).children().each( function(index1, element){
			
			var NewID = element.tagName.toString();
			//if (root <=2  ) alert(NewID);

			NewID = NewID.replace('/ /gi',"");
			NewID = NewID.replace('/[object/',"");
			NewID = NewID.replace('/]/',"");

			var NewIDName = root + "_" + NewID + "_k" + key1 + "i" + key2;
			//Create and assign ID if not exists
			if( $(this).attr('id') == ''){  
				switch(NewID){
					case "DIV":
					case "TABLE":
					case "TD":
						$(this).attr('id', NewIDName); 
						break;
						
					default:
					
				}
			}
			
			key1++;
			key2++;
			
			//if this element has children, recursivly do the same for it.
			$(this).children().each( function(index2,element){
				//Call this recursivly for each child element.
				buildIDTree( $(this) , root, key1+index1, key2+index1+index2);
			});
			
		});		
	}
}
/*************************************/