﻿/* PROTOTYPES */
// create a data store for previously calculated results
Function.prototype.memoized = function(key){
	this._value = this._value || {};
	
	return (this._value[key] !== undefined)
		? this._value[key]
		: this._value[key] = this.apply(this, arguments);
};
// returns a function whos calculated results will be memoized
Function.prototype.memoize = function(){
	var fn = this;
	return function(){
		return fn.memoized.apply(fn, arguments);
	};
};

function showNav(){
	$('#topNav_products_link').parent().children('.dropShadowWrapper').show();//stop(true,true).animate({height:'show',opacity: .9},10);//,function(){ dropme(this); });
}

function hideNav(){
	$('#topNav_products_link').parent().children('.dropShadowWrapper').hide();//$('#topNav_products_link').stop(true,true).animate({height:'hide',opacity: 0},10);//,function(){ $(this).next().remove(); });
}		

function showLanguages(){
	$('#languages').stop(true,true).show();//animate({height:'show',opacity: .9},100);//,function(){ dropme(this); });
}

function hideLanguages(){
	$('#languages').stop(true,true).hide();//animate({height:'hide',opacity: 0},1);//,function(){ $(this).next().remove(); });
}	

function executeSearch(searchTerm)
{
	var $pageURL = window.location.href;
	var $lastIndex = $pageURL.indexOf('/', $pageURL.indexOf('/', $pageURL.indexOf('/',$pageURL.indexOf('/') + 1) + 1) + 1);
	var $languageSite = $pageURL.substring(0, $lastIndex);
	var $searchURL = $languageSite + '/Pages/UltradentSearch.aspx?k='+ searchTerm + '&cs=This Site&u=' + $languageSite;
	window.location = $searchURL;
}

function searchRedirect(strUrl, value)
{
    strUrl += "?k=" + escapeProperly(value);
    window.location = strUrl;
    return false;
}

function MainSearchKeyDown(e, url, value)
{
	if (IsKeyDownSubmit(e))
    {
        SearchRedirect(url, value);
	    return false;
   	}
	return true;
}

/* Events*/

//added on 3/5/11
var frmBtnClick = false;
//end 3/5/11 code

function updateEvent(id){
	$('#colorBoxTitle').html($('#ColorBoxTitle').val());
	$('#eventInfo').html($('#event'+id).html());
	$('#Event').val($('#eventName'+id).html());
	
	$('#popupFormFields :input').val(''); /* Clear the inputs each time the lightbox is shown. */
	$('#popupFormFields :input').css('border','1px solid #D7D7D7');	/* Remove red borders from fields */
	$('#formError').hide(); /* Hide any previous error messages */
	$('#popupFormFields').show(); /* Show input fields */
	$('.button.surveySubmit').show(); /* Show submit button */	
	$('#sucessMessage').detach(); /* Remove success*/
	
	//added on 3/5/11
	$('#hideOnSubmit').show();
	$('#welcomeText').show();
	frmBtnClick = false;
	//end 3/5/11 code
	//added on 3/7/11
	$('div#popupForm > div.dividedHeading').hide(); //hides default heading
	$('#colorBoxTitle').show();
	$('#colorBoxConfirmTitle').hide();
	//end 3/7/11 code
}

//Popup Forms onSubmit
function SubmitProcess()
{
	$('#RequestInformation').colorbox.resize();
	/* This function required in SubmitProcess to attach the surveySubmit.click code each time, since the buttons are recreated. */
	$('.button.surveySubmit').click(function() {
	    $('.button.surveySubmit').hide();
		$('#dummySubmit').show();
		frmBtnClick = true;
	});
	if($('.button.surveySubmit').is(':hidden')){
		$('#popupFormFields').hide(); /* hide input fields */
	}
	
	//added on 3/5/11 - show h1 tag and success message
	if(frmBtnClick && $('#popupFormFields').is(':hidden')){ //if button clicked, and no error
		$('#popupFormFields').show()
		$('#hideOnSubmit').hide();
		$('#welcomeText').hide();
		$('#colorBoxTitle').hide(); //added on 3.7.11
		$('#colorBoxConfirmTitle').show(); //added on 3.7.11
		$('#RequestInformation').colorbox.resize();
	}
	//end 3/5/11 code
}

/*Search Stuff*/

	if(typeof(MSOLayout_MakeInvisibleIfEmpty) == "function") {MSOLayout_MakeInvisibleIfEmpty();}
		
	(function($){
		$(document).ready(function(){
		
						
			$('[id^="product-kittypes"]').each(function(){
				var $availKits = null;
				$(this).click(function(e){
					e.preventDefault();
					//extract product-id from anchor id
					var proid = this.id.match(/\S+-(\d+)/)[1],
						$lineItem = $(e.target).parents('.lineItem');
					if($availKits)
					{
						toggleKittypes();	
					}
					else 
					{
						//else load kittypes into document
						var $pageURL = $(this).attr('href').toLowerCase();
						var $languageSite = $pageURL.substring($pageURL.indexOf('/', 9) + 1, $pageURL.length - ($pageURL.indexOf('/', 9) + 1));
						$languageSite = $languageSite.substring(0, $languageSite.indexOf('/'));
						if ($pageURL.match('/pages/')==null) $pageURL += '/pages/default.aspx';
						$.ajax({
							url: '/_vti_bin/KitTypesService.svc/GetKitTypes/' + $languageSite + '?productURL=' + $pageURL,
							dataType: 'xml',
							cache: false,
							context: $lineItem,
							beforeSend: function()
							{
								$availKits = $('<div class="availableKitTypes loading">' + translateText("Loading", window.location.href) + '</div>');
								this.append($availKits);
							},
							complete: function(xmlHttpRequest){
								//load kittypes into doc and apply accordion ui
								$availKits
									.empty()
									.removeClass('loading')
									.hide();
								var kitTypeHTML = '<h3>' + translateText("Kit Types", window.location.href) + '</h3><span class="accordion-view-all">' + translateText("View All", window.location.href) + '</span><ul class="accordion kitTypesList">';
								var $kitTypes = $(xmlHttpRequest.responseXML).find("KitType").each(function()
							 	{
							 	 	var $thumbnailSRC = $($(this).find('Image').text()).attr('src');
							 		var $thumbnailALT = '';
							 		if ($thumbnailSRC != null) 
							 		{
							 			$thumbnailSRC = "src='" + $thumbnailSRC + "'"; //don't add an img src if the image doesn't exist.
							 			$thumbnailALT = $(this).find('Title').text();
							 		}

							 		kitTypeHTML +=
								 		'<li class="lineItem accordion-item">' + 
								 			'<h2 class="accordion-label">' + $(this).find('Title').text() + '<span class="itemId">#'+$(this).find('ItemNumber').text()+'</span></h2>' +
								 			'<div class="accordion-content">' + 
												"<img " + $thumbnailSRC + " class='thumbnail' alt='" + $thumbnailALT +"'>" + 
												'<div class="details">' + 
													'<dl class="contents">' +
														'<dt>' + translateText("Item", window.location.href) + ' #:</dt>' +
														'<dd>' + $(this).find('ItemNumber').text() + '</dd>' + 
														'<dt>' + translateText("Contents", window.location.href) + ':</dt>';
														$(this).find("Content").each(function()
														{
															kitTypeHTML += '<dd>' + $(this).text() + '</dd>';
														});
													kitTypeHTML = kitTypeHTML + '</dl>'+
												'</div>'+
												'<div class="itemActions">'+
													'<a href="#" class="productBuy button">' + translateText("Where to Buy", window.location.href) + ' »</a>'+
													'<a class="link2 requestInfo" href="#" onclick="requestInfoKitType(' + "'" + $(this).find('ItemNumber').text() + "', '" + location.href.split("/")[3].toLowerCase() + "'" + ');return false;">' + translateText("Request Info", window.location.href) + ' »</a>'+
												'</div>'+
											'</div>' +
										'</li>';
								});
								
								kitTypeHTML  += '</ul>';	
								$availKits.html(kitTypeHTML);
								Products();
								var viewText = translateText("View All", window.location.href), 
									hideText = translateText("Hide All", window.location.href);
								$availKits.accordion({ toggleButton: [viewText, hideText] });
									
								toggleKittypes();
							},
							error: function(){
								$availKits.removeClass('loading')
									.addClass('error')
									.append('There was an error while loading the kit types for this product.');
							},
							contentType: "text/xml; charset=\"utf-8\""
						});
					}
					function toggleKittypes() {
						//if kittypes have been loaded then toggle display
						var hideText = translateText("Hide Product Kit Types", window.location.href);
						var viewText = translateText("View Product Kit Types", window.location.href);
						var target = e.target,
							label = (target.childNodes[0].nodeValue.indexOf('View') !== -1)
								? hideText + ' \u00BB'
								: viewText + ' \u00BB'; // \u00BB == unicode value for &raquo >>;
						$availKits.slideToggle(250);
						$(target).html(label);
					};
				});
			});
			
		});
	})(jQuery);
	
	var translateText = (function(keyValue, PageURL, includeLink) {
			if (!includeLink) var includeLink = "true";
			var translation = null;
			$.ajax({
				url: '/_vti_bin/WebServices.svc/TranslateString/' + keyValue + '?PageURL=' + PageURL.substring(PageURL.indexOf('/', 9), PageURL.indexOf('.aspx') + 5) + "&includeLink=" + includeLink,
				dataType: 'xml',
				cache: false,
				async: false,
				complete: function(xmlHttpRequest){
					translation = $(xmlHttpRequest.responseXML).find("Translation").text(); 
				},
				contentType: "text/xml; charset=\"utf-8\""
			});
			return translation;	
	}).memoize();
	
								
	/* remove the refiner parameter if user clicks on top level refiner*/
	$(document).ready(function(){
		$('#topNav').children('li').mouseenter(function(){ $(this).children('.dropShadowWrapper').show(); });
		$('#topNav').children('li').mouseleave(function(){ $(this).children('.dropShadowWrapper').hide(); });
					
		$('#languagesHover').mouseleave(function(){hideLanguages();});	
		
		$('.EditModeSectionLink').click(function()
		{
			$(this).next('.EditModeSection').slideToggle(600);
		});

		$('.searchRefine').click(function() {
			if($(this).attr('id')=='all') {
				window.location = "UltradentSearch.aspx?k=" + getParameterByName('k') + "&cs=" + getParameterByName('cs') + "&u=" + getParameterByName('u');
			}
			if($(this).attr('id')=='products') {
				window.location = "SearchProducts.aspx?k=" + getParameterByName('k') + "&cs=" + getParameterByName('cs') + "&u=" + getParameterByName('u');
			}
			if($(this).attr('id')=='kittypes') {
				window.location = "SearchKitTypes.aspx?k=" + getParameterByName('k') + "&cs=" + getParameterByName('cs') + "&u=" + getParameterByName('u');
			}
			if($(this).attr('id')=='resources') {
				window.location = "SearchResources.aspx?k=" + getParameterByName('k') + "&cs=" + getParameterByName('cs') + "&u=" + getParameterByName('u');
			}


		  /*if(getParameterByName('s')=='') {
		  	window.location = removeParameter(window.location.href,'r') + '&s='+$(this).attr('id');
		  }
		  else{
		  	window.location = removeParameter(removeParameter(window.location.href,'r'),'s')+ '&s='+$(this).attr('id');
		  }*/
		});
		if(window.location.toString().indexOf('SearchKitTypes.aspx')!=-1) {
			$('#kitTypeRefiner').show();
		}
		if(window.location.toString().indexOf('SearchResources.aspx')!=-1) {
			$('#resourceRefiner').show();
		}
		//This will make the translation links work even if they are inside another clickable element.
		$('.translationLinkSpan').click(function(event){
		    event.stopImmediatePropagation();
		});
		$('.s4-searchbox-QueryPrompt').each(function(index) {
			if ($(this).val()=='Enter keyword / sku' || $(this).val()=='')
			{
				$(this).val(translateText("Search Text", window.location.href, 'false'));
			}
		});		

		
	/*moving the refiner around*/
	//$('#SRCHREF').appendTo($('#prodrefine'));
	//$('#SRCHREF').removeClass();
	//($('#SRCHREF').has('li').length?'':$('#SRCHREF').remove())
		
	/*put search keyword in headers*/	
	//$('em.keyword').text('"'+ getParameterByName('k')+'"');
		
	/*helper functions */	
	
		function getParameterByName(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 decodeURIComponent(results[1].replace(/\+/g, " "));
		}
		/*put search keyword in headers*/	
		$('em.keyword').text('"'+ getParameterByName('k')+'"');

		function removeParameter(url, parameter)
		{
		  var urlparts= url.split('?');
		  if (urlparts.length>=2)
		  {
		      var urlBase=urlparts.shift(); //get first part, and remove from array
		      var queryString=urlparts.join("?"); //join it back up
		
		      var prefix = encodeURIComponent(parameter)+'=';
		      var pars = queryString.split(/[&;]/g);
		      for (var i= pars.length; i-->0;)               //reverse iteration as may be destructive
		          if (pars[i].lastIndexOf(prefix, 0)!==-1)   //idiom for string.startsWith
		              pars.splice(i, 1);
		      url = urlBase+'?'+pars.join('&');
		  }
		  return url;
		}
	});
	
	(function(){
 		/**
		 * $.fn.toggleMenu
		 * show/hide menu items in relation to a trigger item identified by a classname of menu-item.
		 * onclick method looks at id of trigger and finds relationship from data-belongs-to attr and toggles those items
		 */
		$.fn.toggleMenu = function(opt){
			var conf = $.extend({
				TOGGLE_ITEM_SELECTOR: 'data-belongs-to',
				ACTIVE_CLASS: 'selected',
				MENU_ITEM_CLASS: 'menu-item',
				closeOpenMenus: true
			}, opt);
			
			return $(this).each(function(){
				
				var selectedMenuItem = null,
					$menu = $(this),
					$toggleItems = $menu.find('['+ conf.TOGGLE_ITEM_SELECTOR +']');
					
				//hide togglable items by default
				$toggleItems.hide();
				
				$menu.click(function(e){
					var target = e.target;
    				
	    			if($(target).hasClass(conf.MENU_ITEM_CLASS))
	    			{
	    				e.preventDefault();
    					if(conf.closeOpenMenus && target !== selectedMenuItem) 
    					{
	    					$toggleItems.slideUp();
    					}
	    				
	    				//toggle selected item class
	    				$menu.find('.' + conf.MENU_ITEM_CLASS).removeClass(conf.ACTIVE_CLASS);
	    				$(target).addClass(conf.ACTIVE_CLASS);
	    				
	    				//display target item
	    				$menu.find('['+ conf.TOGGLE_ITEM_SELECTOR + '="' + target.id + '"]').slideToggle(200);
    					selectedMenuItem = target;
	    			}
				});
			});
		};
		
	})(jQuery);
						            	


	$(document).ready(function(){
		// make sharepoint ribbon persistent
		//$('#s4-ribbonrow').stickyHeader('#s4-bodyContainer');
	
		$('#questionsAnswersList').toggleMenu();
	
		//toggle kittypes content
		$('.groupedResults #kitTypeResults .contents').hide(function(){
			var $contents = $(this);
			var contentsText = translateText("Show Contents", window.location.href);
			$('<a href="">' + contentsText + '</a>').insertBefore($contents).click(function(e){
				e.preventDefault();
				$(this).html($contents.is(':visible') ? contentsText : translateText("Hide Contents", window.location.href));
				$contents.slideToggle();
			});
		});
		$('#footerDetails a').colorbox({
			onOpen: function() {
		     	populateFooterItem($(this).attr('id').replace('footerItem', ''));
	    	},
            transition:'none',
            width: 800, height: 'auto',
            resize: true,
            scrolling: false,
            inline: true
       }); 
	});
	
	function populateFooterItem (id)
	{
		$.ajax({
			url: '../_vti_bin/WebServices.svc/FooterItem/' + id,
			dataType: 'xml',
			cache: true,
			async: false,
			complete: function(xmlHttpRequest){	
				$('#footerDiv .footerTitle').html($(xmlHttpRequest.responseXML).find("FooterItem").find("Title").text());
				$('#footerDiv .body').html("<p>" + $(xmlHttpRequest.responseXML).find("FooterItem").find("Body").text() + "</p>");
			},
			error: function(){
				$('#footerDiv').removeClass('loading').addClass('error').html('There was an error while loading this data.');
			},
			contentType: "text/xml; charset=\"utf-8\""
		});
	}



