/*	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(){
	// All existing HTML's will need the ss_accordion.js added
	var accordion = null;
	if($("reviewAccordion"))
    	accordion = new Accordion("reviewAccordion", 1);

	$$('.footnoteContentArea').invoke('hide');


	/*
	*	Reviews tab JS calls.
	*
	*
	*
	*
	*/
	//Initializing the Tab buttons
	$$('.reviewsTabButtons').each(function(element){

		Event.observe(element, 'click', function(e){
			//First unclick all buttons
			$$('.reviewsTabButtons').each(function(element){
					$(element).removeClassName('active');
			})
			$$('.reviewTabSections').each(function(element){
				$(element).hide();
			})

			var thisButtonElement = Event.element(e);
			//click the buttons
			$(thisButtonElement).addClassName('active');
			//show corresponding tabs
			var elementName = $(thisButtonElement).readAttribute('href').substring(1);
			$(elementName).show();
			ReviewsTabUtils.sfrWithinReviews();
			Event.stop(e);

		})

	})

	$$('.showHideFootnotesLink').invoke('observe', 'click', function(evt){

		//alert('clicked');

		if($(this).hasClassName('active') == true)
		{
			$(this).removeClassName('active');
			$(this).innerHTML ="VIEW FOOTNOTES";
			$('footNoteContent').hide();
		}
		else
		{
			$(this).addClassName('active');
			$(this).innerHTML ="HIDE FOOTNOTES";
			$('footNoteContent').show();
		}


	});

	$$('.reviewTabSections').each(function(e){
		e.hide();
	})

	if ($$('.reviewTabSections')[0])
	{
		$$('.reviewTabSections')[0].show();
		$$('.reviewsTabButtons')[0].addClassName('active');
	}

	/*
	* End tab buttons
	*
	*
	*/

	/*
		This next function reset/initializes the interaction within the Expert/Consumer reviews tabs
	*/
	ReviewsTabUtils.setupReviewTabInteractions();

	/*
		This next section initiates the custom select boxes
	*/

	/*
		Setup the pagination
	*/

	ReviewsTabUtils.setupPagination('.paginationContainer');

	$$('.jcCustomSelect').each(function(e){
		new jcCustomSelect(e.readAttribute('id'), null)
	})

	//Setup Sfr	Flash Font
	sIFR.replace(AvantGardeBook, {
	  selector: '.sfrReviewsHeader',
	  css: ['.sIFR-root { color: #3e4041; font-size: 32px;}'],
	  wmode: 'transparent',
	  offsetTop: 5,
	  preventWrap:true,
	  forceSingleLine: true
	});
	ReviewsTabUtils.sfrWithinReviews();

	/*
	*	Reviews tab JS calls.
	*
	*
	*
	*
	*/

	sIFR.replace(AvantGardeBook, {
		  selector: '.sifrCategorySectionTitle',
		  css: ['.sIFR-root { color: #44B3E1; font-size: 24px;}'],
		  wmode: 'transparent',
		  offsetTop: 5,
		  preventWrap:true,
		  forceSingleLine: true
	});

	// RICO AJAX CALLS WILL NEED TO GO HERE:
	
	
	// We need to set our default image
	// First thing we're always going to do is set our default product detail tab:

	// First need to check for a tabname in the url parameters ('tab')
	var paramTabName = getURLParameter('tab');
	var isOverviewTab = false;
	if(paramTabName){
		// Remove trailing anchor links appended to URL Param
		if(paramTabName.indexOf('#') > 0){
			paramTabName = paramTabName.substring(0, paramTabName.indexOf('#'));
		}

		// first, let's turn all our Nav Tab elements back to off:
		$$('a.productDetailTabNavLink').invoke('removeClassName', 'activeTab');
		$$('.productDetailTab').invoke('removeClassName', 'defaultTab');

		$$('.productDetailTab').invoke('hide');

		switch(paramTabName){
			case 'overviewTab':
				$('tabNavOverview').addClassName('activeTab');
				isOverviewTab = true;
				break;
			case 'featuresTab':
				$('tabNavFeatures').addClassName('activeTab');
				break;
			case 'specificationsTab':
				$('tabNavSpecifications').addClassName('activeTab');
				break;
			case 'galleryTab':
				$('tabNavGallery').addClassName('activeTab');
				break;
			case 'reviewsTab':
				$('tabNavReviews').addClassName('activeTab');
				break;
			case 'accessoriesTab':
				$('tabNavAccessories').addClassName('activeTab');
				break;
			case 'compatabilityTab':
				$('tabNavCompatability').addClassName('activeTab');
				break;
			default:
				$('tabNavOverview').addClassName('activeTab');
				isOverviewTab = true;
				break;
		}

		// ... and finally, let's turn on the layer that we want to show, while turning off all the
		// others with the class "productDetailTab":
		toggleLayer(paramTabName, 'productDetailTab');

		// For Reviews ,we initialize the SFR text
		ReviewsTabUtils.sfrWithinReviews();
	}
	else{
		if($$('.productDetailTab')[0])
		{
			$$('.productDetailTab')[0].addClassName('defaultTab');
			toggleDefaultElement('defaultTab', 'productDetailTab');
			isOverviewTab = true;
		}
	}
	/*	Related Event Listeners:  Setting Default Elements for color collapse
	 *	--------------------------------------------------------------------------------
	*/

	// Initialize our Vanity and Model Color:
	ourDefaultSKU = $$('.colorChipLink.activeChip').invoke('readAttribute', 'id');
	if ($(ourDefaultSKU[0]))
	{
		ourCurrentVanityName = $(ourDefaultSKU[0]).innerHTML;

		productDetailColorCollapse(ourDefaultSKU[0]);
	}

	// Let's initialize our Product Image Source and filepath:
	ourDefaultImageSource = $('productDetailActiveImage').src;

	if(isOverviewTab){
		$$('a.productDetailTabNavLink')[0].addClassName('activeTab');
	}

	$$('a.colorChipLink').invoke('observe', 'mouseover', function(evt){

		$('currentVanityName').innerHTML = $(this).innerHTML;

	});// end ColorChip Hover Event Listener

	$$('a.colorChipLink').invoke('observe', 'mouseout', function(evt){

		$('currentVanityName').innerHTML = ourCurrentVanityName;

	});// end ColorChip MouseOut Event Listener

	/*	PRODUCT DETAIL TAB EVENT LISTENERS:
	 *	--------------------------------------------------------------------------------------------------
	*/
	$$('a.productDetailTabNavLink').invoke('observe', 'mouseover', function(evt){

		ourSiblings = $(this).siblings();
		ourSiblings[0].addClassName('activeTab');

	});


	$$('a.productDetailTabNavLink').invoke('observe', 'mouseout', function(evt){

		ourSiblings = $(this).siblings();
		ourSiblings[0].removeClassName('activeTab');

	});


	$$('a.productDetailTabNavLink').invoke('observe','click', function(evt){

		// first, let's turn all our Nav Tab elements back to off:
		$$('a.productDetailTabNavLink').invoke('removeClassName', 'activeTab');

		// next, let's turn the tab we clicked on to have an "active" state showing the tab highlighted:
		$(this).addClassName('activeTab');

		// ... and finally, let's turn on the layer that we want to show, while turning off all the
		// others with the class "productDetailTab":
		toggleLayer(($(this).readAttribute('rel')), 'productDetailTab');

		// For Reviews ,we initialize the SFR text
		ReviewsTabUtils.sfrWithinReviews();

	});//end ProductDetail Active Tab Event Listener

	/*  COLOR COLLAPSE - NON FLASH CONTENT EVENT LISTENER:								   !!! READ ME !!!
	 *	--------------------------------------------------------------------------------------------------

	*/
	$$('a.colorChipLink').invoke('observe', 'click', function(evt){


		// We need to highlight the chip we want to outline while removing the outline on the previous active chip
		$$('a.colorChipLink').invoke('removeClassName', 'activeChip');
		$(this).addClassName('activeChip');

		ourSKU = $(this).readAttribute('id');

		productDetailColorCollapse(ourSKU);
		setWriteAReviewUrl(ourSKU);


	});//end colorChipLink Event Listener

	$$('.additionalImageLink').invoke('observe', 'click', function(evt){
			$('productDetailActiveImage').src =  $(this).readAttribute('data-imageName') + ".png";
		});

	// Hide all additional accessories and compatible products with class defaultHiddenProducts
	$$('.defaultHiddenProducts').each(
		function(currentUL){
			currentUL.hide();
		}
	);

	$$('a.viewHiddenProducts').invoke('observe','click', function(evt){
			myId = $(this).readAttribute('relatedDataId');

			if($(myId).style.display == 'none')
			{
				$(myId).show();
				$(this).innerHTML="Close";
			}
			else
			{
				$(myId).hide();
				$(this).innerHTML="View all " + $(this).readAttribute('productCount') + " products";
			}
			Event.stop(evt);
		});

	//Initialize the Ajax for Reviews
	initReviewsAjax();

	// initiate wishlist links
	initAddToWishListAjax();

	$$('.wishlistLink').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;
		});
		$$('.subProductPrice').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){

			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});
	}

	$$("ul.jcCustomSelectList li").each(function(element){
        	if(element.parentNode && element.parentNode.id && (element.parentNode.id == 'consumerReviewsSortBy-jcCustomSelectList' || element.parentNode.id == 'consumerReviewsShowReview-jcCustomSelectList') && element.childNodes[0]){

                	Event.observe(element.childNodes[0], 'click', function(evt){
                  		submitReviewsSearch(0,element.parentNode.id,Event.element(evt).parentNode.readAttribute('value'));
                	});
          	}
      	});

    /*	BRT 7.13.09 - 	Added to similate the "View All Reviews" link functionality
     *					This should address defect 1944.
    */
	/*AJ 12.04 - adding review tab calls and changing spelling of id being associated with event */

	if ($('productViewReviewsLink'))
	{
		Event.observe($('productViewReviewsLink'), 'click', function(){
			
	         // first, let's turn all our Nav Tab elements back to off:
			$$('a.productDetailTabNavLink').invoke('removeClassName', 'activeTab');
			$$('.productDetailTab').invoke('removeClassName', 'defaultTab');
			$$('.productDetailTab').invoke('hide');

			//bring up the reviewsTab
			toggleLayer('reviewsTab', 'productDetailTab');
			//highlight the reviewstab nav
		    $('tabNavReviews').addClassName('activeTab');

			// For Reviews ,we initialize the SFR text
			ReviewsTabUtils.sfrWithinReviews();
			
			//ie fix
			var browser=navigator.appName;
			if(browser!="Microsoft Internet Explorer")
			{
				HTMLElement.prototype.click = function() {
				var evt = this.ownerDocument.createEvent('MouseEvents');
				evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
				this.dispatchEvent(evt);
				}
			}
		});// End productViewsReviewsLink Event Listener
	}

		// ADD TO CART AND WISHLIST OMNITURE ADDITIONS
		$$('.ctaGrouping .produtDetailCTALink').each(function(addToCart, index){
			// GO THROUGH EACH SKU'S ADD TO CART AND WISHLIST
			if(addToCart && addToCart.tagName=='A'){
				Event.observe(addToCart, 'click', function(e){
					trackAddToShoppingCart($$('.productSku')[index].innerHTML);
				});
			}
		});

		$$('.ctaGrouping .wishlistLink').each(function(addToWishlist, index){
			// GO THROUGH EACH SKU'S ADD TO CART AND WISHLIST
			if(addToWishlist && addToWishlist.tagName=='A'){
				Event.observe(addToWishlist, 'click', function(e){
					trackAddToWishList($$('.productSku')[index].innerHTML);
				});
			}
		});
		
		// Add footnotes class to footnotes - no class or Id placed on the <a> tag so we gotta do it this way.  - BRT
		$$('a[href="javascript:showFootnotes();"]').invoke('addClassName', 'footNoteLink');
		
		//Load Product Review Photos
		loadReviewPhotos();
		
		if(window.parent.name=='telesales')
		{
			$$('.writeAReviewHRef').each(function(element){
				if(!$(element).hasClassName('invisibleElement')){
					$(element).addClassName('invisibleElement');
				}
			});
		}
		
		

});//end Window Load Event Observer.

//Dealer locator
function intializeLocatorForm(partnum)
{ 
	partnum=partnum.replace(/_/g, "/");
	
	//alert('js test for locator form initialized.');

 if($('lightwindow_contents'))
 {
 
 	//alert('event observe initiated.');
 
  $('lightwindow_contents').select('.zipCodeSubmitLink').each(function(e){
   
   Event.observe(e, 'click', function(){
   
   	//alert('click event observe triggered');
    
    var ourZipCode = $$('.zipCodeField')[1].value;
    
    //var ourZipCode = $(this).parentNode.parentNode.previous().value;
    
    //alert(ourZipCode);
    
    var ourLink = '/webapp/wcs/stores/servlet/CategoryDisplay?catalogId=10551&storeId=10151&langId=-1&identifier=S_Retailers_with_Inventory';
    //$(this).href= ourLink + '?cii_sZip=' + ourZipCode +'&cii_sSKU='+partnum+'&cii_nRuleGroupID=2548&cii_nRadius=25';
    
    var ourFullSource = ourLink + '&zipCode=' + ourZipCode +'&sku='+ partnum;
    
    $(this).href= ourFullSource;
    
    //$('lightwindow_contents').innerHTML = '<iframe src="'+ ourFullSource +'" width="918" height="670">';
    
    /*myLightWindow.activateWindow({
		href: ourFullSource, 
		width: 918,
		height: 670
	});   */
    
   });
   
  });
  return(false);
 }
}//dealer locator

/*
	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)
	{
		if (element.hasClassName('subProductPrice'))
		{
			if (price)
			{
				newHtml += price;
			}
		} else
		{
			if (origPrice)
			{
				var dollarIdx = origPrice.indexOf("$");
				var decimalIdx = origPrice.indexOf(".");

				newHtml += '<div class="originalPricing">';
				newHtml += '<p class="productPrice">';
				newHtml += '<span class="strikeThrough">';
				newHtml += '<span class="productCurrency">$</span>';
				newHtml += '<span class="productDollars">';
				newHtml += origPrice.substring(dollarIdx+1,decimalIdx);
				newHtml += '</span>';
				newHtml += '<span class="productCents">';
				newHtml += origPrice.substr(decimalIdx);
				newHtml += '</span>';
				newHtml += '<span class="clearfix"></span>';
				newHtml += '</span>';
				newHtml += '<span class="clearfix"></span>';
				newHtml += '</p>';
				newHtml += '</div>';
			}

			if (price)
			{
				var dollarIdx = price.indexOf("$");
				var decimalIdx = price.indexOf(".");

				newHtml += '<p class="productPrice">';
				newHtml += '<span class="productCurrency">$</span>';
				newHtml += '<span class="productDollars">'
				newHtml += price.substring(dollarIdx+1,decimalIdx);
				newHtml += '</span>';
				newHtml += '<span class="productCents">'
				newHtml += price.substr(decimalIdx);
				newHtml += '</span></p>';
			}
			if (finance)
			{
				newHtml += '<p class="productFinancing">';
				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');

		        element.addClassName('hidden');
    			
		}else if (element.hasClassName('productDetailPrimaryCTA'))
		{
			var anchorElement =  $('SKU_' + productId + 'ProductDetailCTAText');

			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;
	}

	newHtml = '';
	var inventoryElement = $('SKU_' + productId + 'InventoryStatus');
	if (inventoryElement)
	{
		if (inventoryElement.hasClassName('inventoryStatusGroup'))
		{
			newHtml += '<p id="productInventoryStatus">';
			newHtml += buttonObject.statusMessage;
			newHtml += '</p>';
			newHtml += '<p id="estimatedShipDate">';
			if (buttonType != 'end_of_life')
			{
				if (buttonObject.shipDateMessage != '')
				{
					newHtml += buttonObject.shipDateMessage;
				} else
				{
					newHtml += buttonObject.atpMessage;
				}
			}
			newHtml += '</p>';

		}

		inventoryElement.innerHTML = newHtml;
	}

}

function setWriteAReviewUrl(ourSKU)
{
var sku=ourSKU.replace('SKU_','');

$$('.writeAReviewHRef').each(function(element){
	if(writeAReviewURL && $(element).href)
		{
		$(element).href=writeAReviewURL.replace(/__PID__/g, sku);
		}
});





}