/*	SONY | SONY STYLE.COM - [MODAL OF FUNCTIONALITY NAME]
 *	Author(s): 	Branden Thompson	| Front End Architect , Branden.Thompson at am dot sony dot com
 *				Jonathan Cheung 	| Sr. Flash Developer , Jonathan.Cheung at am dot sony dot com
 *
 *	Date:		April 17, 2009
 *
 *	JS FILE PRE-CONDITIONS:
 *	-------------------------------------------------------------------------------------------------
 *
 *		- Prototype must be included before this .js (or included functions) is referenced.
 *
 *
 *
 *	FUNCTIONALITY THAT THIS JS WILL PROVIDE
 *	-------------------------------------------------------------------------------------------------
 *
 *	This file will allow us to strip the DOM level2 events that are used ON ALL FILES ON SONY STYLE
 *	Examples would include: AjaxInit()
*/


Event.observe(window, 'load', function(){

	// 	A. - Let's declare all of our 'global' variables within the scope of this event listener.
	//		 this is so we do not have to constantly create instanced copies of variable that we're
	//	     only every going to need to use at one time, and therefore simply serves as 'swap space'
	//		 having one common swap area for all elements make the code perform more efficiently
	//		 since we're recycling memory.

	// STANDARD FEATURES LIST VARIABLES:
	// ----------------------------------------------------------------------------------------------

	var ourShowText = "View Available Options";
	var ourHideText = "Close Available Options";
	var hideFeaturesClass ="collapseFeatures";
	var showFeaturesClass ="expandFeatures";

	var myViewNowOverlayIdSwapSpace = '';

	// COLOR CHIPS & VANITY COLOR NAME MANAGEMENT VARIABLES:
	// ----------------------------------------------------------------------------------------------
	var colorButtonMatrix = '';
	var theRGBs = '';
	var redValue = '';
	var greenValue = '';
	var blueValue = '';
	var ourVanityNameSwapSpace = '';

	// DEFAULT LAYER INITIALIZATION CALLS:
	// ----------------------------------------------------------------------------------------------

	toggleDefaultElement('defaultSku','productCornerArea');
	toggleDefaultElement('defaultSku','availableProductModelNumber');
	toggleDefaultElement('defaultSku','productBadgesList');
	toggleDefaultElement('defaultSku','wishlistCTAGroup');
	toggleDefaultElement('defaultSku','priceGroup');

	$$('.viewNowOverlay').invoke('hide');

	//toggleDefaultElement('defaultSku','');

	//	This is our colorChips Event Listener:
	//	---------------------------------------------------------------------------------------------
	$$('a.colorChipLink').invoke('observe', 'click', function(evt){

		//	1. - Initialize all of our local variables for this particular instance:

		var myLocalId = $(this).readAttribute('id');
		var myProductDefaultId = $(this).readAttribute('data-defaultId');
		var myVanityName = $(this).innerHTML;

		var myCurrentDefaultId = myProductDefaultId.substring(myProductDefaultId.lastIndexOf('_')+1);
		var myCurrentProductId = myLocalId.substring(myLocalId.lastIndexOf('_')+1);

		// 	1b. - Let's initialize all or hexValue/Background-Color variables and CSS strings:

		var myHexValue = $(this).getStyle('background-color');
		// ie6 fix.  if hex value was not converted to rgb, convert.
		if (myHexValue.charAt(0) == "#")
		{
			var rgbValues = hex2num(myHexValue);
			myHexValue = "rgb(" + rgbValues[0] + ", " + rgbValues[1] + ", " + rgbValues[2] + ")";
		}
		var myButtonsDefaultHexValue = $('SKU_' + myCurrentDefaultId + '_ctaButton').getStyle('background-color');
		var myDefaultStyle = "background-color:" + myButtonsDefaultHexValue;
		var myHoverStyle = "background-color:" + myHexValue;
		var myCTAButtonsDefaultTextStyle = $('SKU_' + myCurrentDefaultId + '_ctaButtonText').getStyle('color');
		var myCTAButtonHoverTextStyle = '';
		var myCTAButtonsShineStyle = '';

		//	1c. - Now, let's scrub/convert our HEX value into values suitable for making calculations
		//		  When we're done, we should have 3 integer values like 255, 255, 255:

		colorButtonMatrix = myHexValue.replace("rgb(","");
		colorButtonMatrix = colorButtonMatrix.replace(")","");
		theRGBs = colorButtonMatrix.split(", ");
		redValue = parseFloat(theRGBs[0]);
		greenValue = parseFloat(theRGBs[1]);
		blueValue = parseFloat(theRGBs[2]);

		//	1d. - We need to do some calculations to determine whether or not we need to define both
		//		  a hoverClass State for the button (to change the shine) and the text (to make it dark).
		//		  We're going to do this on the fly so it's tied to our correct element.

		if((eval(redValue + greenValue)) >= 460 || (eval(greenValue + blueValue)) >= 460 || (eval(redValue + greenValue + blueValue)) >= 600)
		{
			// the button is "really light," so let's make the text and button shine black.
			myCTAButtonHoverTextStyle = "darkText";
			myCTAButtonsShineStyle = "CTAButtonOn";
		}

		//	2. - Remove the activeChip class from all of our "sibling" colorchips and append
		//		 the class to colorChip we just clicked:

		$$('#' + myProductDefaultId + '_availableColors .colorChipLink').invoke('removeClassName', 'activeChip');
		$(this).addClassName('activeChip');

		//  3. - Set our both the innerHTML of the Vanity Name Space as well as set our swap space
		//		 variable for our mouseout listener later:

		ourVanityNameSwapSpace = myVanityName;
		$(myProductDefaultId + '_vanityColorName').innerHTML = myVanityName;

		//	4. - Let's show the correct Model Number, and hide the rest:

		$$('#' + myProductDefaultId + '_availableModelNumbers .availableProductModelNumber').invoke('hide');
		$(myLocalId + '_modelNumber').show();

		//	5. - Now we're going to need to be able to treat the CTA Button colors, as well as show the
		//		 correct CTA Button, and Hide the others:
		$$('#' + myProductDefaultId + '_ctaSection .wishlistCTAGroup').invoke('hide');
		$(myLocalId + '_ctaButtonGroup').show();

		//  5a. - show price
		$$('#' + myProductDefaultId + '_priceSection .priceGroup').invoke('hide');
		$(myLocalId + '_priceGroup').show();
		
		// 	5b  - Show / Hide related product badges:
		//  BRT - 7.13.09 - Code added for Defect 2005
		$$('#' + myProductDefaultId + '_badgesArea .productBadgesList').invoke('hide');
		if($(myLocalId + '_badgesList')){$(myLocalId + '_badgesList').show();}
		
		// 	5c. - Corner Callouts - Code added from Ed for Defect #2006
		
		$$('#' + myProductDefaultId + '_cornerCalloutList .productCornerArea').invoke('hide');
		//this check is added because the li's are added only if new is set
		if($(myLocalId + '_newCornerCallout')){$(myLocalId + '_newCornerCallout').show();}          
		
		//this check is added because the li's are added only if pricedrop is present
		if($(myLocalId + '_priceCornerCallout')){$(myLocalId + '_priceCornerCallout').show();} 
        
		
		
		//	5c. - Now we need to set up the mouseover / mouseout listeners for these specific buttons:

		Event.observe($('SKU_' + myCurrentProductId + '_ctaButton'), 'mouseover', function(){

			$(this).setStyle(myHoverStyle);
			$(this).addClassName(myCTAButtonsShineStyle);
			$('SKU_' + myCurrentProductId + '_ctaButtonText').addClassName(myCTAButtonHoverTextStyle);
			
		});

		Event.observe($('SKU_' + myCurrentProductId + '_ctaButton'), 'mouseout', function(){

			$(this).setStyle(myDefaultStyle);
			$(this).removeClassName(myCTAButtonsShineStyle);
			$('SKU_' + myCurrentProductId + '_ctaButtonText').removeClassName(myCTAButtonHoverTextStyle);

		});

		setProductDisplayUrl(myLocalId);
		
	});// end color chip CLICK event listener



	//	This is our colorChips Event Listener for mousing over a colorchip:
	//	---------------------------------------------------------------------------------------------
	$$('a.colorChipLink').invoke('observe', 'mouseover', function(evt){

		// 	1. - Initialize our local variables that we'll need:

		var myProductDefaultId = $(this).readAttribute('data-defaultId');
		var myVanityName = $(this).innerHTML;

		// 	2. - Set what's currently in the Vanity Name Space as our "swap":

		ourVanityNameSwapSpace = $(myProductDefaultId + '_vanityColorName').innerHTML;

		//	3. - Replace the Vanity Name with what our chip is:

		$(myProductDefaultId + '_vanityColorName').innerHTML = myVanityName;


	});// end color chip MOUSE OVER event listener



	//	This is our colorChips Event Listener for when we mouse off a colorchip:
	//	---------------------------------------------------------------------------------------------
	$$('a.colorChipLink').invoke('observe', 'mouseout', function(evt){

		//	1. - Grab our Default Id so we can "return" the vanity Name to it's previous clicked state:

		var myProductDefaultId = $(this).readAttribute('data-defaultId');

		// 	2. - Replace the Vanity Name from our MouseOver text back to our last clicked value:

		$(myProductDefaultId + '_vanityColorName').innerHTML = ourVanityNameSwapSpace;

	});// end color chip MOUSE OUT event listener



	//	This is our show/hide standard features bullet list listener:
	//	---------------------------------------------------------------------------------------------
	$$('.standardFeatureToggle').invoke('observe', 'click', function(evt){

		//	1. - Let's grab both our local id and our "defaultSku":

		var ourDefaultText = $(this).innerHTML;
		var ourTogglerParentId = $(this).readAttribute('data-defaultId');

		// 2. - Now we can check the approrpiate element to see if it is either hidden or shown
		//		and toggle the layer on/off as well as change the toggle text:

		if($(ourTogglerParentId + '_standardFeatures').style.display == 'none')
		{
			$(ourTogglerParentId + '_standardFeatures').show();
			$(this).innerHTML = ourHideText;
			$(this).removeClassName(showFeaturesClass);
			$(this).addClassName(hideFeaturesClass);
		}
		else
		{
			$(ourTogglerParentId + '_standardFeatures').hide();
			$(this).innerHTML = ourShowText;
			$(this).removeClassName(hideFeaturesClass);
			$(this).addClassName(showFeaturesClass);
		}
	});// end Standard Features List Toggler Event Listener

	//	This is our show/hide viewNow:
	//	---------------------------------------------------------------------------------------------
	$$('.productListingImage').invoke('observe', 'mouseover', function(evt){

		myViewNowOverlayIdSwapSpace = $(this).readAttribute('rel');
		//alert(myViewNowOverlayIdSwapSpace);

		$(myViewNowOverlayIdSwapSpace + '_viewOverlay').show();

		Event.observe($(myViewNowOverlayIdSwapSpace + '_viewOverlay'), 'mouseout', function(){
			$(this).hide();
		})

	});


	// initiate wishlist links
	initAddToWishListAjax();

	$$('.listingWishlistLink').each(function(e){
		Event.observe(e, 'click', function(evt){

			var element = Event.element(evt)
			var elementId = element.id;
			elementId = elementId.replace('wishlist_','');

			addItemToWishlist(element);
			ajaxEngine.sendRequest('SYAddToWishListAjax', {method:'post', parameters: getAddToWishListAjaxParams(elementId)});

			Event.stop(evt);
		});
	});

	// initiate pricing
	if (isUserInEpp())
	{
		initPricingAjax();

		var counter = 0;
		var priceArray = new Array();
		$$('.priceFinancingGroup').each(function(element){

				var elementId = element.id;
				elementId = elementId.replace('SKU_','');
				elementId = elementId.replace('PriceAndFinancingOptions','');

				priceArray.push("catEntryId_" + counter + "=" + elementId);

				++counter;
		});

		if (counter > 0)
		{
			var productIdsForPrice = priceArray.join("&");
			ajaxEngine.sendRequest('SYGetContractUnitPrices', {method:'post', parameters: productIdsForPrice + "&" + baseUrlParameters});
		}
	}

	// initiate product buttons
	initProductButtonsAjax();

	var counter = 0;
	var productArray = new Array();
	$$('.CTAButton').each(function(element){

		if (element.hasClassName('productListingPrimaryCTA'))
		{
			var elementId = element.id;

			elementId = elementId.replace('SKU_','');
			elementId = elementId.replace('_ctaButton','');

			productArray.push("catEntryId_" + counter + "=" + elementId);

			++counter;
		}
	});

	if (counter > 0)
	{
		var productIdsForButtons = productArray.join("&");
		ajaxEngine.sendRequest('SYGetProductButtonMessageFromCacheAjax', {method:'post', parameters: productIdsForButtons + "&URL=SYGetSKUButtonMessageAjaxResponseView&" + baseUrlParameters});
	}



	//Setup Sfr	Flash Font
	sIFR.replace(AvantGardeBook, {
		  selector: '.productAccListingMainHeader',
		  css: ['.sIFR-root { color: #44B3E1; font-size: 22px;}'],
		  wmode: 'transparent',
		  offsetTop: 0,
		  offsetBottom: 0,
		  preventWrap:true,
		  forceSingleLine: true
	});
	
	
	sIFR.replace(AvantGardeBook, {
		  selector: '.productListingMainHeader',
		  css: ['.sIFR-root { color: #999999; font-size: 32px;}'],
		  wmode: 'transparent',
		  offsetTop: 5,
		  offsetBottom: 0,
		  preventWrap:true,
		  forceSingleLine: true
	});
	
	
	// This is for any PromoSpots in the right rail.
 	sIFR.replace(AvantGardeMedium, {
  		 selector: '.rightRailSpotTitle',
  		 css: ['.sIFR-root { color: #000000; font-size: 13px }'],
  		 wmode: 'transparent',
  		 preventWrap: false,
  		 offsetTop: 2,
 		 forceSingleLine: false 
	});




}); //end Window Load Event Observer:


/*
	Setup markup for Price section. May be different for each page.
*/
function displayPriceSection(productId, priceObject)
{
	var origPrice = priceObject.orgPrice;
	var price = priceObject.price;
	var finance = priceObject.finance;

	var newHtml = '';

	var element = $('SKU_' + productId + 'PriceAndFinancingOptions');
	if (element)
	{
		newHtml += '<p class="productPriceRange">';
		if (origPrice)
		{
			var dollarIdx = origPrice.indexOf("$");
			var decimalIdx = origPrice.indexOf(".");

			newHtml += '<span class="strikeOut">';
			newHtml += '<span class="productCurrency">$</span>';
			newHtml += '<span class="currencyUnits">';
			newHtml += origPrice.substring(dollarIdx+1,decimalIdx);
			newHtml += '</span>';
			newHtml += '<span class="currencySubUnits">';
			newHtml += origPrice.substr(decimalIdx);
			newHtml += '</span>';
			newHtml += '</span>';
		}

		if (price)
		{
			var dollarIdx = price.indexOf("$");
			var decimalIdx = price.indexOf(".");

			newHtml += '<span class="productCurrency">$</span>';
			newHtml += '<span class="currencyUnits">'
			newHtml += price.substring(dollarIdx+1,decimalIdx);
			newHtml += '</span>';
			newHtml += '<span class="currencySubUnits">'
			newHtml += price.substr(decimalIdx);
			newHtml += '</span>';
		}
		newHtml += '</p>';

		if (finance)
		{
			newHtml += '<p class="financingCalloutMessage">';
			newHtml += finance;
			newHtml += '</p>';
			/*
			var dollarIdx = finance.indexOf("$");
			var slashIdx = finance.indexOf("/");

			newHtml += '<p class="productFinancing">As low as ';
			newHtml += '<span class="monthlyRate">';
			newHtml += finance.substring(dollarIdx,slashIdx);
			newHtml += '</span>/month**</p>';
			*/
		}

		element.innerHTML = newHtml;
	}
}


function displayProductButtonSection(productId, buttonObject)
{
	var newHtml = '';
	var buttonType = buttonObject.buttonType;
	var element = $('SKU_' + productId + '_ctaButton');
	if (element)
	{
		if (buttonType == 'end_of_life')
		{
			element.removeClassName('CTAButton');
		}else if (element.hasClassName('productListingPrimaryCTA'))
		{
			var anchorElement =  $('SKU_' + productId + '_ctaButtonText');

			if (anchorElement)
			{
				var urlLink = buttonObject.buttonLink;
				if (urlLink == "")
				{
					urlLink="javascript:void(0);";
				}
				anchorElement.href = urlLink;
				anchorElement.innerHTML = buttonObject.buttonText;
			}
			/*
			newHtml += '<a href="';
			newHtml += urlLink;
			newHtml += '"';
			newHtml += 'class="produtDetailCTALink" rel="">';
			newHtml +=
			newHtml += '</a>';
			*/
		}

		//element.innerHTML = newHtml;
	}

}


function setProductDisplayUrl(ourSKU)
{
var catIndex=ourSKU.lastIndexOf('_');
var catId=ourSKU.substring(catIndex+1);
var suffix=ourSKU.substring(0,catIndex).replace('PRODUCT_GROUP','');
if(ourSKU && ($('productDisplayHrefViewNow'+suffix) || $('productDisplayHrefDescription'+suffix)))
	{
		var purl=$('productDisplayHrefViewNow'+suffix).href;
		if(purl.indexOf('productId=')!=-1){		
           string='productId=';
		}else if(purl.indexOf('categoryId=')!=-1){	
			string='categoryId=';
		}else if(purl.indexOf('LBomId=')!=-1){	
			string='LBomId=';
		}		
		
		var start=purl.indexOf(string);
		if(start!=-1){
			var end=purl.indexOf('&',start);
			if(end==-1) end=purl.length;
			purl=purl.replace(purl.substring(start,end),string+catId);
			}
		
		if($('productDisplayHrefViewNow'+suffix)) {$('productDisplayHrefViewNow'+suffix).href=purl;}
		if($('productDisplayHrefDescription'+suffix)) {$('productDisplayHrefDescription'+suffix).href=purl;}
	}
}


/* -------------------------------------------------------------------------------------------
	Method:				hex2num
	
	Arguments:			hex (string - 6 character Hexidecimal)
	
	Pre-Conditions:		* hex must be a six digit hexidecimal number pairing
						* '#' can either be included or omitted
						
	Post-Conditions:	function will turn #000000 into 0, 0, 0
------------------------------------------------------------------------------------------- */
function hex2num(hex) {
        if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
        hex = hex.toUpperCase();
        var hex_alphabets = "0123456789ABCDEF";
        var value = new Array(3);
        var k = 0;
        var int1,int2;
        for(var i=0;i<6;i+=2) {
                int1 = hex_alphabets.indexOf(hex.charAt(i));
                int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
                value[k] = (int1 * 16) + int2;
                k++;
        }
        return(value);
}