/**
 * Cookbooks Explorer widget controls for 
 * handling the height and position of the SWF object
 * 
 * These methods are called with ExternalInterface by the SWF object 
 * when it enters different states.
 */
var CookbookExplorerWidget = {
	mask: jQuery('#CookbookExplorerMask'),
	animationDuration: 500,
	
	closedMaskHeight: "250px",
	openMaskHeight: "360px",
	
	closedWidgetPosition: "-25px",
	openWidgetPosition: "0px"
};

CookbookExplorerWidget.expand = function(){
	jQuery('#CookbookExplorerMask').animate({height:this.openMaskHeight}, {duration: this.animationDuration});
	jQuery('#CookbookExplorer').animate({top:this.openWidgetPosition}, {duration: this.animationDuration});
};
 
CookbookExplorerWidget.compact = function(){
	jQuery('#CookbookExplorerMask').animate({height:this.closedMaskHeight}, {duration: this.animationDuration});
	jQuery('#CookbookExplorer').animate({top:this.closedWidgetPosition}, {duration: this.animationDuration});
};


//linear transform from a scale to another
scale_value = function(from_scale, to_scale, value) {
	var piece1 = ((value - from_scale[0]) / (from_scale[1] - from_scale[0])) * (to_scale[1] - to_scale[0])
	var toret = piece1 + to_scale[0]
	return toret
}

var Cookbooks = {};
Cookbooks.runSimilarityIndicator = function(){
	/**
	 * Similarity indicator for related articles
	 */
	var $ = jQuery;
	var raw_sim = []
	$('.similarity').each(function(){
		
		//get the similarity value as a number
		var simVal = Number($(this).find('.similarityValue').text(), 10);
		raw_sim.push(simVal);
		
	});

	var raw_sim_max = Math.max.apply( Math, raw_sim);
	var raw_sim_min = Math.min.apply( Math, raw_sim);

	idx = 0;

	var sims = []
	$('.similarity').each(function(){
		
		//get the similarity value as a number
		var simVal = Number($(this).find('.similarityValue').text(), 10);
		
		//compute the indicator width based on similarity value

		if (false) { //ADR: change here to revert
			var indicatorWidth = (simVal*20 > 100)
				? 100
				: simVal * 20;
		} else {
			var indicatorWidth = scale_value([raw_sim_min, raw_sim_max], [10.0, 100.0], simVal);
			sims.push(indicatorWidth)
		}
		idx++;
			
		//assign the indicator width
		$(this).find('.liniarIndicator').css('width', indicatorWidth);
	});
};

(function($){
	
	Array.prototype.inArray = function (value) {
		var i;
		for (i=0; i < this.length; i++) {
			if (this[i] === value) {
				return true;
			}
		}
		return false;
	};
	
	//wrapper for browser sniffing / capabilities check methods
	var browser = {};
	
	/**
	 * Check if the browser has a CSS property and is capable of using it via DOM scripting
	 * 
	 * @param {String} propetyName
	 * 				   name of the css property to check for in the browser
	 * 
	 * @return {Boolean}
	 */
	browser.hasCssProperty = function(propertyName){
		//look for a dashed CSS property like max-height
		var pName = propertyName.split("-");
		
		//convert dashed CSS properties (max-height) to camelCase DOM properties (maxHeight)
		if (pName.length > 1){
			//start building the DOM property name
			propertyName = pName[0];
			
			for (var i=1; i<pName.length; i++){
				
				//Uppercase the first letter
				propertyName += pName[i].substr(0,1).toUpperCase(); 
				
				//Concat the rest of the word, without the first letter
				propertyName += pName[i].substr(1);
			}
		}
		
		var testEl = document.createElement('div');
		return (testEl.style[propertyName] !== undefined)
			? true 
			: false;
	};
	
	/**
	 * Check if the browser supports the adjacent CSS selector (el + el).
	 * 
	 * Trick: browsers that support the max-height property also support the adjacent selector
	 * 
	 * @return {Boolean}
	 */
	browser.supportsAdjacentSelector = function(){
		return browser.hasCssProperty("max-height");
	};
	
	
		
	$('document').ready(function(){
		
		//attach behavior for search boxes to prevent default value submit
		
//		$('#cbSearchBox input[type="text"]').searchBoxBehavior(); // this was moved into the footer.
		$('#adcSearchBox input[type="text"]').searchBoxBehavior();
		
		//attach close button behavior for prompt messages
		$('a.but_close').bind('click',function(e){
			e.preventDefault();
			$(this).parent().slideUp('fast');
			return false;
		});
		
		//there are trimmed tags on the page
		if ($('.summaryList .trimmed')[0]){
			
			//build hover target and attach hover behavior
			$('.summaryList .trimmed').each(function(){
				
				//hover container
				var $hoverEl = $('<div>').addClass("hover");
				var $hoverContent = $('<a>').attr({
					href:this.href //keep the link consistent with the trigger	
				});
				
				$hoverContent.text(this.title).html(); //take the title property of the trigger as the contents for the hovered link
				
				$hoverEl.append($hoverContent);
				
				//append the hover container at the same level with the trigger
				$(this).parent().append($hoverEl);
				
				//attach toggle hover behavior
				$(this).toggleHover($hoverEl);
			});
		}
		
		$('.recipeList .recipeContainer').hoverBlock();
		
		//tab navigator for uberhomepage
		if ($(".tabNavigation li")[0] && $(".tabTargets>div")[0]){
			var tabNavi = new TabNavigator(jQuery);
			
			tabNavi.triggers = $(".tabNavigation li a");
			tabNavi.targets = $(".tabTargets>div");
			tabNavi.init();
		}
		
		//all technologies expander on uberhomepage
		if($("#expandTagsPanel")) {
			
			$("#expandTagsPanel").bind("click", function(e) {
				e.preventDefault();
				$("#technology_homepage_cloud_more").toggle();
				$("#expandTagsPanel").html(($("#expandTagsPanel").html() == "More") ? "Less" : "More");
				return false;
			});	
		}
		
		
		//add CSS styles to adjust for incapable browsers
		if (!browser.supportsAdjacentSelector()){
			$('#globalfooter li+li').addClass('sibling');
		}

		//use friendly URLs for the search event
		$('#cbSearchBox').bind('submit', function(){
			$form = $(this);
			var searchBy = jQuery.trim($('#searchTagName').val());
			//Make sure the stripped characters below are the same as the ones
			//specified in the search controller, doGoogleSearch method.
			searchBy = searchBy.replace(/-|\+|\.|&|<|>|'|"|\//g, '');
			var newAction = $form.attr('action') + "/" + encodeURIComponent(searchBy);				
			$form.attr('action', newAction);			
			$('#searchTagName').attr('disabled', true);
		});
		
		/**
		 * Fix for browsers incapable of advanced pseudo-classes
		 */
		$('.pipeSeparator li:first-child').addClass('first-child');
		$('.pipeSeparator li:last-child').addClass('last-child');


		$('#tagList .ico_delete')
			.bind('mouseover', function(){
				$(this).parent().addClass('delete');
			})
			.bind('mouseout', function(){
				$(this).parent().removeClass('delete');
			})
			.bind('click', function(e){
				removeTag($(this).parent());
				setTagSearchFormAction($('#tagSearchForm'));
				submitTagSearchForm();
				return false;
			});
			
		$('#tagList a')
			.bind('click', function(e){
				showSearchProgress();
			});
			
		$('#tagSearchForm').bind('submit', function(){
			showSearchProgress();
			setTagSearchFormAction($('#tagSearchForm'));
		});
			
		function submitTagSearchForm(){
			$('#tagSearchForm')[0].submit();
		}
		
		function showSearchProgress(){
			$('#tagSearchForm').slideUp('fast', function(){
				$('#tagSearchMessage').slideDown('fast');
			});
		}
		
		function removeTag($container){
			if (!$container || typeof $container !== 'object'){
				throw new TypeError('Invalid parameter $container. Expected jQuery object. Got: '+typeof $container);
			}
			
			//do not send the new tagname
			$('#newTagName').attr('disabled',true);
			
			//disable cookbooksTagNames DOM for current element.				
			$container.find("input[name='cookbooksTagNames']").remove();
			
			//enable removeTagName DOM for current element.	
			$container.find("input[name='removeTagName']").removeAttr("disabled");
		}
		
		function setTagSearchFormAction($form){
			if (!$form || typeof $form !== 'object'){
				throw new TypeError('Invalid parameter $form. Expected jQuery object. Got: '+typeof $form);
			}
			
			var tags = [];
			
			/**
			 * Clean the tag value for the server call
			 * @param {String} tag
			 * 				   value of the tag to be cleaned
			 * 	
			 * @return {String}
			 */
			var sanitizeTag = function(tag){
				var t = jQuery.trim(tag.toLowerCase());
				return encodeURIComponent(t);
			};
			
			$("input[name='cookbooksTagNames']").each(function(){
				tags.push(sanitizeTag($(this).val()));
			});
			
			if ($('#newTagName:not(:disabled)').val()){
				tags.push(sanitizeTag($('#newTagName').val()));
			}
			
			var newAction = $form.attr('action') + "/" + tags.join(',');					
			$form.attr('action', newAction);
		}







		
		/*
		 * ADC Accordion Menu behavior binding
		 */
		$('.accordion-controller')
			.bind('mouseover', function(){
				$(this).addClass('mouseover');
			})
			.bind('mouseout', function(){
				$(this).removeClass('mouseover');
			})
			.toggle(
				function(){
					$(this).parent().addClass('opened').end().next().handleAccordionData();
				},
				
				function(){
					$(this).parent().removeClass('opened').end().next().slideUp('fast');
				});

		//Omniture hooks
		if ($('.tabNavigation')[0]) {
			$('.tabNavigation a[name="new"]').bind("click", function() {
				if (s && s.pageName) {
					s.pageName = "Cookbooks: " + $('#techName').val() + ": Home: Whats New Tab";
					void(s.t());
				}
			})
			$('.tabNavigation a[name="top"]').bind("click", function() {
				if (s && s.pageName) {
					s.pageName = "Cookbooks: " + $('#techName').val() + ": Home: Top Content Tab";
					void(s.t());
				}
			})
		}
		
		
		
		if ($('form[name="addForm"] :submit')) {
			
			var iframeSufix = "___Frame";
								
			$('form[name="addForm"] :submit').bind("click", function(e) {
				var tempId = $('#templateId') ? $('#templateId').val() : -1;
				omniturePageName = (tempId == 12) ?
					"Cookbooks: Create a Recipe Form: Published" :
					"Cookbooks: Request a Recipe Form: Published";
				// Store the FCKeditor value in the corresponding
				// hidden input for an accurate validation.
				if($('iframe[id*="'+iframeSufix+'"]')){
					try {
					var iframeId = $('iframe[id*="'+iframeSufix+'"]').attr("id");
					var elementId = iframeId.replace(iframeSufix,"");
					$("#"+elementId+"").val(cbFCK.getFCKcontent());
					}catch(e){}						
				}
			});
			
			/**
			$('#savePost').bind("click", function(e) {
				var tempId = $('#templateId') ? $('#templateId').val() : -1;
				omniturePageName = (tempId == 12) ?
					"Cookbooks: Create a Recipe Form: Saved" :
					"Cookbooks: Request a Recipe Form: Saved";
			});
			**/
		}
		
		
		if ($('form[name="editForm"] :submit')) {
			
			var iframeSufix = "___Frame";
			
			$('form[name="editForm"] :submit').bind("click", function(e) {
				
				//	Check if the edit is marked as a recipe request answer.
				if ($('#workflow') && $('#workflow').val() == "isAnswer") {
					omniturePageName = "Cookbooks: Answer a Request Form: Published";
					
				}else {
					var tempCode = $('#templateCode') ? $('#templateCode').val() : "";
					omniturePageName = (tempCode == "cookbooks_recipe") ?
						"Cookbooks: Edit a Recipe Form: Published" :
						"Cookbooks: Edit a Recipe Request Form: Published";
				}	

				// Store the FCKeditor value in the corresponding
				// hidden input for an accurate validation.
				if($('iframe[id*="'+iframeSufix+'"]')){
					try {
					var iframeId = $('iframe[id*="'+iframeSufix+'"]').attr("id");
					var elementId = iframeId.replace(iframeSufix,"");
					$("#"+elementId+"").val(cbFCK.getFCKcontent());
					}catch(e){}						
				}				
			});
			
			/**
			$('#savePost').bind("click", function(e) {
				var tempCode = $('#templateCode') ? $('#templateCode').val() : "";
				omniturePageName = tempCode == "cookbooks_recipe" ?
					"Cookbooks: Edit a Recipe Form: Saved" :
					"Cookbooks: Edit a Recipe Request Form: Saved";
			});
			**/
		}
	});
})(jQuery);
