/*	SONY | SONY STYLE.COM - GLOBAL HEADER EVENT LISTENERS
 *	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
 *	-------------------------------------------------------------------------------------------------
 *
 *	[DESCRIPTION HERE]
*/

/* ===================================================================================================
 * BEGIN Global Navigation Setup
 * ! Initialize the GlobalNavigation here
 * First we create the name of the variable to store the menu
 * ===================================================================================================
*/
//Global nav variable
var Sonystyle_global_naviation;
/* ! Next we setup the onLoad listener to initialize the globalNav  */
Event.observe(window, 'load', function(){

	//	BRT 7.26.09 - Because we do not have an event listener file for the category/subcategory page,
	//	this is the only place I can place this particular sIFR event listeners.  In subsequent releases,
	//	we should address this:

		// 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
		});

		//	BRT 12.4.09 - We need to set up the hover state for the search submit button:
		//
		//	NOTE TO ISSA DEV!
		//
		//	Once ready to inmplement on the WCS Encvironment, uncomment the basepath and delete the extra quotes:
		//
		if ($('siteSearchSubmitButton')) { // Fix for 4595

			ss_basepath = "/wcsstore/SonyStyleCanadaStorefront/";

			Event.observe($('siteSearchSubmitButton'), 'mouseover', function(evt){
				$(this).src = ss_basepath + "img/global/search_submit_arrow_red.gif";
			});

			Event.observe($('siteSearchSubmitButton'), 'mouseout', function(evt){
				$(this).src = ss_basepath + "img/global/search_submit_arrow.gif";
			});

		} //end fix for 4595

	// ================================================================================================================================================================
	// ! Initializing the global navigation
	//	Menu ( DIV NAME, NAME OF GLOBALE VAIRABLE HOLDING THE NAV, ONSTATE CLASS NAME, HAS SUBNAV CLASS NAME, HIGHLIGHT CLASS NAME )
	// ================================================================================================================================================================
 	if ($('logoLoginSearchSection'))
 	{
	 	Sonystyle_global_naviation = new Menu('globalNavigation', 'Sonystyle_global_naviation', "Active", "hasOptions", "standBy");

		// =================================================================
		// ! The following function initializes the sonystyle header links
		// =================================================================
	 	HeaderUtils.init();

	 	// ============================
		// ! Setup the global message
		// ============================
	 	HeaderUtils.initGlobalMessage()

		// =================================
		// ! Initialize Login/Logoutrollover
		// =================================
    // MQC 5423: No mouse-over functionality for SOCAN so this is not needed
		HeaderUtils.loginInit();
	}

	// =================================
	// ! Initialize Globale Flash text
	// =================================
	initGlobalSiFR();

	// =================================
	// ! Initialize Search Box values
	// =================================
	if ($('WC_CachedSidebarDisplay_FormInput_searchTerm_In_CatalogSearchForm_1'))
	{
		var searchBoxElement = $('WC_CachedSidebarDisplay_FormInput_searchTerm_In_CatalogSearchForm_1');
		if (searchBoxElement.value=='Search Products' && !searchBoxElement.hasFocus ){
			searchBoxElement.focus();
		}

		// Prepopulate keyword field
		if (document.location.pathname.indexOf('SearchCatalog') != -1 || document.location.pathname.indexOf('StoreSearch') != -1 ) {
			var keyword = '';
			if (document.location.search.indexOf('keyword') != -1 ) {
				keyword = document.location.search.match(/keyword=([^&]+)/)[1];
			} else if (document.location.search.indexOf('Ntt') != -1 ) {
				keyword = document.location.search.match(/Ntt=([^&]+)/)[1];
			}

			//replace + with blank
			keyword = keyword.replace(/\u002b/gi," ");

			//replace unicode with its actual character representation
			var tempStr = "";
			var lastIdx = 0;
			var percentOccured = false;
			for(var i=0; i<keyword.length; i++){
				if(keyword.charAt(i) == '%'){
					percentOccured = true;
					tempStr += keyword.substring(lastIdx,i);
					tempStr += String.fromCharCode(parseInt("0x" + keyword.substr(i+1,2)));
					lastIdx = i+3;
					i=i+2;	//i+2 since i will be incremeneted by one in for loop.

				}
			}

			if(percentOccured == true) {
				keyword = tempStr + keyword.substring(lastIdx);
			}

		searchBoxElement.value = keyword
	}
		/*Event.observe($('WC_CachedSidebarDisplay_FormInput_searchTerm_In_CatalogSearchForm_1'), "blur", function(e){
			var element = Event.element(e)
			if(element.value=='' && !element.hasFocus){
				element.focus();
			}
		})*/

		// =================================
		// ! Clear Search Box values
		// =================================
		/*Event.observe($('WC_CachedSidebarDisplay_FormInput_searchTerm_In_CatalogSearchForm_1'), "click", function(e){
			var element = Event.element(e)
			if(element.value=='Search'){
				element.value='';
			}
		})*/
	}

	// =================================
	// ! Submit Search Box validation
	// =================================
	if ($('CatalogSearchForm'))
	{
		Event.observe($('CatalogSearchForm'), "submit", function(e){
			var element = Event.element(e)
			if(element.keyword.value=='Search'){
				element.keyword.value='';
			}
			if (!prepareSearch(this)) Event.stop(e);
		})
	}
	// =====================================================
	// ! Adding Omniture tracking code to all Hero banners
	// =====================================================
	$$('a.categoryHeroBannerCTA').each(function(element){

		Event.observe($(element), 'click', function(evt){
			//If there's not a link for the CTA we trigger just the trackCMSpot function
			if (
				$(this).href.indexOf("#") == 0 ||
				$(this).href.indexOf("javascript:") > -1 ||
				typeof(element.onclick) == "function"
				)
			{
				trackCMSpot($(this).id);
			}else{
				//reads the href and rel to pass to the function
				_cmspotObject.trackCMSOmniture($(this).href, $(this).id);
				//Stops href from being followed
				Event.stop(evt);
			}
		});
	});
}, false);
/* ===================================================================================================
 * END Global Navigation Setup
 * ===================================================================================================
*/

ss_search_autocomplete = {
	autoCompleteController : {
		setActions : function(){
			var me = this;
			// change default text on click for auto-complete
			jQuery(".newTopHeaderSearchBar").click(function(event){
				var s = trimString(this.value);
				if(s == "Search Products" || s == "Enter text and try again"){
					this.value="";
				}
			});

			jQuery(".newTopHeaderSearchBar").keydown(function(event){
				var s = trimString(this.value);
				if(s == "Search Products" || s == "Enter text and try again"){
					this.value="";
				}
				jQuery(".newTopHeaderSearchBar").unbind('keydown');
			});

			// if nothing entered put the default text back
			jQuery(".newTopHeaderSearchBar").blur(function(event){
				if(trimString(this.value)==""){
					this.value = "Search Products";
				}
			});

			// Submit form on button click
			jQuery('#newSiteSearchSubmitButton').click(function(event){
				var s = trimString(jQuery(".newTopHeaderSearchBar").val());
				if(s != "Enter text and try again" && s != "Search Products" && s != ""){
					jQuery('#CatalogSearchForm').submit();
				}
			});

			//jQuery(".newTopHeaderSearchBar").focus();


			// Adding for defect #9455 to always default to list when switching between languages
			jQuery("#headerLanguageSection a").click(function(){
				setCookie('searchViewPref', 'list');
			});


			/*******************************AUTOCOMPLETE***************************************************************/

			// THIS IS FOR PUTTING THE AUTOCOMPLETE DROPDOWN FURTHER DOWN IN THE DOM. REQUIRED TO WORK IN IE.
				var temp_headerdiv = document.createElement('div');
				temp_headerdiv.className = 'yui-skin-sam';
				temp_headerdiv.innerHTML = '<div class="yui-ac"><div id="searchContainer" class="yui-ac-container"></div></div>';
				if($("sonyStyleWebsite")){
					document.getElementById("sonyStyleWebsite").appendChild(temp_headerdiv);
				}
				else{
					document.getElementById("content").appendChild(temp_headerdiv);
				}
				// END AUTOCOMPLETE DROPDOWN SECTION



				YAHOO.example.ACJson = new function(){
				// Instantiate an XHR DataSource and define schema as an array:
				// ["Multi-depth.object.notation.to.find.a.single.result.item",
				// "Query Key",
				// "Additional Param Name 1",
				// ...
				// "Additional Param Name n"]
				this.oACDS = new YAHOO.widget.DS_XHR("SYSearchAjax", ["ResultSet.suggestionList","value"]);
				this.oACDS.scriptQueryParam = "keyword";

				  this.oACDS.scriptQueryAppend = paramvalues;

				this.oACDS.TYPE_JSON=1; //--
				// Instantiate AutoComplete
				this.oAutoComp = new YAHOO.widget.AutoComplete("WC_CachedSidebarDisplay_FormInput_searchTerm_In_CatalogSearchForm_1","searchContainer", this.oACDS);
				this.oAutoComp.minQueryLength = 3;
				this.oAutoComp.queryDelay = .3;
				this.oAutoComp.autoHighlight = false;
				this.oAutoComp.animSpeed = 0.2;
				  this.oAutoComp.maxResultsDisplayed = 7;

				this.oAutoComp.formatResult = function(oResultItem, sQuery) {
					// decode and reevaluate text
					oResultItem[0] = this.repairString(decodeURIComponent(oResultItem[0]));

					var returnString = decodeURIComponent(oResultItem[1].value);
					var searchTerm = document.HeaderCatalogSearchForm.keyword.value;
					var pattern = new RegExp(searchTerm + "(?!;)", "i");
					var caseSensitiveTerm = returnString.match(pattern);
					var p_element="";
					var sku_length = returnString.length;

					var categoryString = "";
					var firstEntry = "false";
					var urlItem = decodeURIComponent(oResultItem[1].url);
					//alert(categoryString + " " + firstEntry);

					returnString = returnString.replace(pattern, "<span class=\"wordMatched\">" + caseSensitiveTerm + "</span>");
					p_element = '<div class=\"autoSearchProductText\">' + returnString + '</div>'; //--

					if (oResultItem[1].categoryname != "") {
							  categoryString = decodeURIComponent(oResultItem[1].categoryname);
							  firstEntry = "true";
					}

					var isNewWindowTxt = "";
					if(oResultItem[1].newWindow == "true")
						isNewWindowTxt = "target=\"_blank\"";

					if(firstEntry == "true")
					{
						//alert(oResultItem[1].url);
						// If this thing has a URL than we need to override the behavior
						if(oResultItem[1].url){
									return      '<h3 class=\"categoryNameTitle\">'+oResultItem[1].categoryname+'</h3><div class=\"listElementWrapper\"><a href=\"'+urlItem+'\" ' + isNewWindowTxt + '>'+p_element+'</a></div>';
						}
						else{
							return '<h3 class=\"categoryNameTitle\">'+oResultItem[1].categoryname+'</h3><div class=\"listElementWrapper\">'+p_element+'</div>';
						}
					}else
					{
						if(oResultItem[1].url){
									return '<div class=\"listElementWrapper\"><a href=\"'+urlItem+'\" ' + isNewWindowTxt + '>'+p_element+'</a></div>';
						}
						else
							return '<div class=\"listElementWrapper\">'+p_element+'</div>';
					}

				};



				this.oAutoComp.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) {

					var pos = YAHOO.util.Dom.getXY(oTextbox);
					YAHOO.util.Dom.setXY(oContainer,pos);

					return true;
				};

				this.oAutoComp.repairString = function(str) {
					var temp_div = document.createElement('div');
					temp_div.innerHTML = str;
					return temp_div.firstChild.nodeValue;
				}
				//define your itemSelect handler function:
				var itemSelectHandler = function(sType, aArgs) {
					var oMyAcInstance = aArgs[0]; // your AutoComplete instance
					var elListItem = aArgs[1]; //the <li> element selected in the suggestion
					//container
					var aData = aArgs[2]; //array of the data for the item as returned by the DataSource

					// log if lookahead category selected
					if (aData[1].id)
					{
						document.HeaderCatalogSearchForm.in_dim_search.value = decodeURIComponent(aData[1].value);
					}
						//removeCookie("SearchResultsCompareCookie");
						document.HeaderCatalogSearchForm.submit();
				};

				var containerCollapseHandler = function(sType, aArgs) {

				};

				  //if (this.oAutoComp.itemSelectEvent) this.oAutoComp.itemSelectEvent.subscribe(itemSelectHandler);
				if (this.oAutoComp.containerCollapseEvent) this.oAutoComp.containerCollapseEvent.subscribe(containerCollapseHandler);

				};

			/*******************************AUTOCOMPLETE***************************************************************/


		},
		init : function(){
			var me = this;
			me.setActions();
		}
	},
	init : function() {
		var me = this;
		jQuery(document).ready(function(){
			jQuery('#CatalogSearchForm').submit( function () {
				removeCookie("SearchResultsCompareCookie");
				return true;
			});
			me.autoCompleteController.init();
		});
	}
}
ss_search_autocomplete.init();
