//	LBi.Custom
//	Working under jQuery 1.21

if ( typeof LBi == 'undefined' ) { self.LBi = {}; }

// trim
String.prototype.trim = function () {
    return this.replace(/^\s*|\s*$/g,'');
}


// LBi.Custom
LBi.Custom = {
	formChanged: false,
	dynamicText: function() {
		var search = document.getElementById("search");
		dynamicText (search);
		//username
		//var userName = document.getElementById("username");
		//dynamicText(userName);
		//password
		//var passWord = document.getElementById("password");
		//dynamicText(passWord);
	},
	trapFormChange: function(e) {
		
		var target;
		
		if (e){
			
			target = e.currentTarget;
			
			if (target == null){
			
				target = e.target;
				
			}
			
		}
		
		// find out if the form has changed 
		if ((!($(target).hasClass('search'))) && (!($("body").hasClass('login')))){
			
			LBi.Custom.formChanged = true;
			
		}
		if($('.formError').css('display') === 'inline'){
			LBi.Custom.formChanged = true;
		}
		if (LBi.Custom.formChanged === true){
			
			$("input").unbind("keyup", LBi.Custom.trapFormChange);
			$("select").unbind("change", LBi.Custom.trapFormChange);
			
			// if the user leaves the form, check to see if they want to
			window.onbeforeunload = function() {
					
				return LBi.Custom.trapFormExit();
			
			}
			
			// clear all inputs of check
			$("input").click(function(){
				
				$("form").submit(function(){
										  
					window.onbeforeunload = function() {
						
						LBi.Custom.trapFormChange();
						
					}
					
				});
				
			});
			
			// clear edit profile links of check
			$(".editProfile ul li a").click(function(){
				
				window.onbeforeunload = function() {
						
					return;
						
				}
				
			});
			
			// clear edit profile links of check
			$(".upperHubContentTeaserProfile ul li a").click(function(){
				
				window.onbeforeunload = function() {
						
					return;
						
				}
				
			});			
			
			// clear for package list in management tool
			$("#managementPackages a").click(function(){
				
				window.onbeforeunload = function() {
						
					return;
						
				}
				
			});
			
			
			$(".sortDataSubResults a").click(function(){
				
				window.onbeforeunload = function() {
						
					return;
						
				}
				
			});
			
			
			$(".packageTree img").click(function(){
				
				window.onbeforeunload = function() {
						
					return;
						
				}
				
			});
			
			
			// put the check back on the search input
			$(".bannerSearch input").click(function(){
				
				$("form").submit(function(){
				
					window.onbeforeunload = function(e) {
					
						return LBi.Custom.trapFormExit();
			
					}
				
				});
			
			});
		}
		
	},
	trapFormExit: function(e) {
		return "Information you entered on this page has not yet been saved.";
	},
	trapFormChangeSetup: function() {
		
		$("input").bind("keyup", function(e){
		
			// make sure the keyup event is not from the user tabbing through the form
			var code;
			
			if (!e) {
				
				var e = window.event;
				
			}
			
			if (e.keyCode !== 9){
				
				// i don't want to check for change on search inputs
				if ($(this).attr('class') !== 'search'){
					
					LBi.Custom.trapFormChange();
					
				}
				
			}
			
		});
		
		$("select").bind("change", LBi.Custom.trapFormChange);
		
	},
	tabSetup: function() {
		$(".tabMenu").each(function(i) {
			$(this).find("a").each(function(i) {
				if (i > 0)
					$($(this).attr("href")).hide();
				
				$(this).click(function() {
					$(this).parents(".tabMenu").find("a").each(function() {
						$($(this).attr("href")).hide();
						$(this).parents("li").removeClass("active");
					})
					$($(this).attr("href")).show();
					$(this).parents("li").addClass("active");
					
					return false;
				})
			})
		})
	},
	
	lookAheadSetup: function(){
		
		// because IE7 starts a new positioning context for every relatively positioned item, inputs are overlapping dropdowns. I need to give each successive form row a lower z-index to get around this
		var setZIndex = 500;
		
		$(".lookAheadControl .search").each(function(i){
													 
			$(this).keyup(function(){
								   
				LBi.Custom.lookAheadCall(this);
				
			});
			
			$(this).parents(".lookAheadControl").find(".results").hide();
			$(this).parents(".lookAheadControl").css('z-index', setZIndex);
			setZIndex = setZIndex - 1;
			
		});
		
		$(".packagePickerControl .advancedOptions a").click(function() {
		
			$(this).parents(".packagePickerControl").find(".advancedPaneWrapper").fadeIn(); 
			
			// Clear the advanced search form
			$(".advancedPaneWrapper").find(":input").val("");
			
			return false;
			
		});
		
		$(".packagePickerControl .advancedPaneHeader a").click(function() {
				
			$(this).parents(".advancedPaneWrapper").fadeOut(); 
		
			return false;
		
		});
		
	},
	
	// reset look ahead function if an update panel is posted back
	lookAheadAJAX: function(){
    
		aspForm = document.getElementById("aspnetForm");
    	
		if(typeof(Sys)!='undefined'){
        
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
           	
				function(){
            
					LBi.Custom.lookAheadSetup();
           	
				}
				
			);
        
		}
    
	},
	
	lookAheadCall: function(caller){
		
		if (caller.value != ''){
			
			$.ajax({
				
				url: '/Templates/Corporate/Util/PackagePickerResults.aspx',
				type: 'POST',
				dataType: 'html',
				data: { 
					'searchTerm': caller.value 
				},
				timeout: 5000,
				error: function(){
					
					alert('Error loading document');
				
				},
				success: function(response){
					
					// make sure there are results in the response before showing the dropdown
					if(response !== ''){
						
						$(caller).parents(".lookAheadControl").find(".results").html(response);
						LBi.Custom.lookAheadSuccess(caller);
						
					}
				
				}
			
			});
		
		}
		
		else {
			
			if (!$(caller).parents(".lookAheadControl").find(".results").is(":hidden")){
				
				
				$(caller).parents(".lookAheadControl").find(".results").removeClass("resultsWithContent");
				$(caller).parents(".lookAheadControl").find(".results").slideUp();
				
			}
			
		}
		
	},
	
	lookAheadSuccess: function(caller) {
		
		var results = $(caller).parents(".lookAheadControl").find(".results");
		
		$(results).addClass('resultsWithContent');
		if (results.is(":hidden")){
			
			results.slideDown();
			
		}
		
		results.find("a").each(function(i) {
			
			$(this).click(function() {
				
				var nodeId = ($(this).attr("class") != '') ? $(this).attr("class").replace("n", "") : "";
				var multipleSelection = ($(this).parents(".lookAheadControl").attr("class").indexOf("lookAheadMultiple") != -1);
				
				LBi.Custom.lookAheadAppendData($(this).parents(".packagePickerControl").find(".data"), multipleSelection, nodeId);
				$(this).parents(".lookAheadControl").find(".search").val($(this).text());
				
				if (!$(this).parents(".results").is(":hidden")){
					
					$(this).parents(".results").slideUp();
					
				}
					
				return false;
				
			});
			
		});
		
	},
	
	// reset look ahead function if an update panel is posted back
	lookAheadAJAX: function(){
    
		aspForm = document.getElementById("aspnetForm");
    	
		if(typeof(Sys)!='undefined'){
        
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
           	
				function(){
            
					LBi.Custom.lookAheadSetup();
           	
				}
				
			);
        
		}
    
	},
	
	// when the package hiearchry form is submitted, the checked values are posted back in an update panel, these need to be caught and passed back to a hidden field on the main page
	packageHiearchySelectAJAX: function(){
    
		aspForm = document.getElementById("aspnetForm");
    	
		if(typeof(Sys)!='undefined'){
        
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
           	
				function(){
            
					LBi.Custom.packageHiearchySelect();
           	
				}
				
			);
        
		}
    
	},
	
	packageHiearchySelect: function(){
		
		var packageDataFrontValue;
		
		// only do this stuff if the user is on the package picker tab
		if($('#tab-4').css('display') === 'block'){
			
			packageDataFrontValue = $('.packageDataFront').val();
		
			// if the hidden field has values, the user has picked packages and these need to be put in the hidden field on the page
			if (packageDataFrontValue !== ''){
			
				$('.packageDataBack').val(packageDataFrontValue);
				$(".packagePickerControl .search").val("Multiple Selections");
				
				//close the panel
				$(".advancedPaneWrapper").fadeOut();
			
			}
			
		}
		
	},
	
	packagePickerAppendData: function(nodeId, textvalue)
	{
	  var dataControl = $(".packagePickerControl").find(".data");
	  LBi.Custom.lookAheadAppendData(dataControl, false, nodeId);
	  $(".advancedPaneWrapper").fadeOut();
	  $(".packagePickerControl").find(".lookAheadControl").find(".search").val(textvalue);
	},
	
	itemExists: function(array, item)
  {
    for (var i = 0; i < array.length; i++)
    {
      if (item == array[i])
        return true;
    }
    
    return false;
  },
	
	selectMultipleOnClick: function(selectedPackages)
	{
     var packages = selectedPackages.split(',');
     
     $("#managementPackages :checkbox").each(function(x)
	   {
	      if ($(this).is(':checked'))
	      {
	        if (!LBi.Custom.itemExists(packages, $(this).val()))
	        {
	          packages.push($(this).val());
	        }
	      }
	      else
	      {
	        if (LBi.Custom.itemExists(packages, $(this).val()))
	        {
	          item = $(this).val();
	          // Need to remove the package
	          var tempPackages = [];
	          for (var i = 0; i < packages.length; i++)
	          {
	            if (packages[i] != item)
	            {
	              tempPackages.push(packages[i]);
	            }
	          }
	          packages = tempPackages;
	        }
	      }
	   });

     var dataControl = $(".packagePickerControl").find(".data");
	   dataControl.val("");
	   
	   for (var i = 0; i < packages.length; i++)
	   {
	    LBi.Custom.lookAheadAppendData(dataControl, true, packages[i].toString());
	   }
	   
//	   $("#managementPackages :checked").each(function(x)
//	   {
//	      LBi.Custom.lookAheadAppendData(dataControl, true, $(this).val());
//	   });
	   
    $(".advancedPaneWrapper").fadeOut();
    $(".packagePickerControl").find(".lookAheadControl").find(".search").val("Multiple Selections");
	},

	lookAheadAppendData: function(dataControl, multipleSelection, nodeId) {
		if (multipleSelection) {
			if (dataControl.val() == "") {
				dataControl.val("'" + nodeId + "'");
			}
			else {
				if (dataControl.val().indexOf("'" + nodeId + "'") == -1)
					dataControl.val(dataControl.val() + "," + ("'" + nodeId + "'"));
			}
		}
		else {
			dataControl.val("'" + nodeId + "'");
		}
	},
	
	facetSelectOnClick: function(facetName)
    {
        $('#' + facetName.replace("~", "\\~") + '_facets input').each(
            function (i) 
            { 
                if ($(this).css('display') == 'none')
                {
                    $(this).css('display','block')
                }
                else
                {
                    $(this).css('display','none')
                } 
            }
        );
        
        var selectItem = $('#' + facetName.replace("~", "\\~") + '_selectmultiple');
        selectItem.text((selectItem.text() == 'Select multiple') ? 'Select single' : 'Select multiple');
    },
    
    facetGoOnClick: function(parentFacetName, hiddenFieldId)
    {
        var checked = []; 
        checked.push(parentFacetName); 
        $('#' + parentFacetName.replace("~", "\\~") + '_facets input').each(
            function (i) 
            { 
                if ($(this).attr('checked') == true) 
                    checked.push($(this).attr('id'));
            }
        ); 
        
        hiddenField = $('#'+hiddenFieldId).val(checked.join(','));
    },
    
    facetShowMoreOnClick: function(facetName)
    {
        expandCollapse(facetName + '_rest'); 
        expandCollapse(facetName + '_topten');
        var item = $('#'+facetName.replace("~", "\\~")+'_showhide');
        item.text((item.text() == 'Show more') ? 'Show top 10' : 'Show more');
    },
	
	floatingDefinitionListHeights: function(){
		
		var viewDefinitionListDds;
		var listWidth;
		var listItemWidth;
		var itemsPerRow;
		var i;
		var rows;
		var firstInRowIndex;
		var j;
		var elemHeight;
		var maxHeight;
		var k;
		var heightToSet;
		var IE6 = false;
		
		// get all the lists of floating items
		var viewDefinitionList = $('.floatingDefinitionList');
		
		// find out if the browser is IE6
		if (jQuery.browser.msie) {
			
			if (parseInt(jQuery.browser.version) < 7){
				
				IE6 = true;
				
			}
			
		}
		 
		for(i = 0; viewDefinitionList[i]; i++){
			 
			// put all the dd into an array
			viewDefinitionListDds = $(viewDefinitionList[i]).children('dd');
			 
			// find the number of items in each row
			listWidth = $(viewDefinitionList[i]).width();
			listItemWidth = $(viewDefinitionListDds[0]).width();
			itemsPerRow = Math.floor(listWidth / listItemWidth);
			
			// find the number of rows
			rows = Math.ceil(viewDefinitionListDds.length / itemsPerRow);
			
			// for each row, find the height of the tallest element
			for(j = 0; j <= rows; j++){
				// get the first element in the row
				firstInRowIndex = j*itemsPerRow;
				
				maxHeight = 0;
				
				// check the heights of all the others in the row
				for(k = firstInRowIndex; k < firstInRowIndex + itemsPerRow; k++){
					
                	if(k < viewDefinitionListDds.length){
						
						elemHeight = viewDefinitionListDds[k].clientHeight - parseInt($(viewDefinitionListDds[k]).css("padding-top"), 10) - parseInt($(viewDefinitionListDds[j]).css("padding-bottom"), 10);
						
						if(maxHeight < elemHeight){
                    		
							maxHeight = elemHeight;
							
						}
            
					}
			
				}
				
				// set all the heights in the row to the tallest
				for(k = firstInRowIndex; k < firstInRowIndex + itemsPerRow; k++){
					
					if(k < viewDefinitionListDds.length){
															 
							heightToSet = maxHeight + 1 + "px";
  
  							if(IE6){
								
     							$(viewDefinitionListDds[k]).css("height", heightToSet);
								
							}
							else{
								
     							$(viewDefinitionListDds[k]).css("min-height", heightToSet);
								
							}
                
					}
            
				}
				
			}
			
		}
		
	},
	
	featuredAnalysisWithImage : function(){
		
		var theImageWidth, theImages, theImage, divToResize, theImageMargin, theContainer;
		
		//find the items 
		var theItems = $('.featuredAnalysis .document');
		var numberOfItems = theItems.length;
		
		// if the list items have an image they need to have a width applied to the div adjacent to the image
		for (var i = 0; i < numberOfItems; i++){
			
			theImages = $(theItems[i]).find('img'); 
			divToResize = $(theItems[i]).find('.featuredAnalysisInfo');
			
			if (theImages.length > 0){
			
				theImage = $(theImages[0]);
			
				// get the width of the image
				theImageWidth = theImage.width();
			
				// get any additional width factors
				theImageMargin = parseInt(theImage.css('margin-right'), 10) + parseInt(theImage.css('margin-left'), 10);
			
				//find the adjacent div and resize it based on the size of the image
				divToResize.width($(theItems[i]).width() - (theImageWidth + theImageMargin));			
		
			}
			else{
				
				divToResize.width('428px');
				
			}
			
		}
	
	}
	
}


// dynamicTex
function dynamicText (t) {
    if (!t) return;
        t.savedText = t.value; // keep track of the original input value
        t.onfocus=function(){
	        this.value = this.value.trim()
	        if (this.value == this.savedText) {
		        this.value = "";
	        }
        }
        t.onblur=function(){
	        this.value = this.value.trim()
	        if (this.value == "") {
		        this.value = this.savedText;
	        }
        }
}




// Set the debug option to true, so form data is not commited enabling you to review the outcome.
//$.validator.setDefaults({
//	debug: true
//});







// DocumentReady
$(document).ready(function() {
// DOM ready functions */
    
    // dynamic form text for search and login inputs
    LBi.Custom.dynamicText();

	// tab setup
	LBi.Custom.tabSetup();
	
	// lookAhead search
	LBi.Custom.lookAheadSetup();
	LBi.Custom.lookAheadAJAX();
	
	// package hiearchy select
	LBi.Custom.packageHiearchySelectAJAX();
	
	// form change setup (disabled until further testing can be done)
	LBi.Custom.trapFormChangeSetup();
	
	// prevent floated definition list items breaking layout
	LBi.Custom.floatingDefinitionListHeights();
	
	// update paragraph size in Featured Analysis list to cater for presence of image
	LBi.Custom.featuredAnalysisWithImage();
	
    // toggle login html
    /*
    $("#loginOverlay").addClass("hide");
    $("a.login").toggle(
        function () {
            $("#loginOverlay").animate({ height: 'show' }, 'fast'); //.animate({ height: 'show', opacity: 'show' }, 'slow');
            $("a.login").addClass('selected');
        },
        function () {
            $("#loginOverlay").animate({ height: 'hide' }, 'fast'); //.animate({ height: 'hide', opacity: 'hide' }, 'slow');
            $("a.login").removeClass('selected');
        }
    );
    */
    
    
    // validate form on keyup and submit
    var o;
    o = $("#loginForm");
    if (o)
    {
        $(o).validate({
	        //As soon as a key within a form field is release then start
	        event: "keyup",
	        // The rules for the individual inputs are defined.
	        rules: {
		        //for id="username"
		        username: {
			        required: true,
                    //rangeLenght Option [minLenght,maxLenght]
			        rangeLength:[4,16]
		        },
		        //for id="password"
		        password: {
			        required: true
		        }
	        },
        	
	        //Here the error messages for all rules are defined.
	        messages: {
		        username: {
			        required: 'Please enter your username',
			        rangeLength: 'Your username must consist of at least 4 and at most 16 characters',
			        notEqualTo: 'Please enter your username'
		        },
		        password: {
			        required: 'Please enter a password',
			        minLenght: 'Your password must consist of at least 4 characters',
			        notEqualTo: 'Please enter your password'
		        }

	        },
        	
	        //Optionally: This message appears, when the rules are met
	        success: function(label) {
		        //label.html('ok').addClass("success");
	        }
        });
    };
    
    
    // validate form on keyup and submit
    o = $("#myTestForm");
    if (o)
    {
	    $(o).validate({
		    //As soon as a key within a form field is release then start
		    event: "keyup",
		    // The rules for the individual inputs are defined.
		    rules: {
			    //for id="username"
			    username: {
				    required: true,
                                    //rangeLenght Option [minLenght,maxLenght]
				    rangeLength:[4,16]
			    },
			    //for id="mail"
			    mail: {
				    required: true,
				    //It is an E-Mail address
				    email: true
			    },
			    //for id="demoPassword"
			    demoPassword: {
				    required: true,
				    minLength: 4
			    },
			    //for id="confirm_demoPassword"
			    confirm_demoPassword: {
				    required: true,
				    minLength: 4,
				    // confirm_demoPassword == demoPassword?
				    equalTo: "#demoPassword"
			    },
			    agree: "required"
		    },
    		
		    //Here the error messages for all rules are defined.
		    messages: {
			    username: {
				    required: 'Please enter your username',
				    rangeLength: 'Your username must consist of at least 4 and at most 16 characters'
			    },
			    demoPassword: {
				    required: 'Please enter a password',
				    minLenght: 'Your password must consist of at least 4 characters'
			    },
			    confirm_demoPassword: {
				    required: 'Please confirm your password',
				    equalTo: 'Please enter the same password as above'
			    },
			    agree: 'Please accept our policy',
			    mail: 'Please enter a valid email address'

		    },
    		
		    //Optionally: This message appears, when the rules are met
		    success: function(label) {
			    //label.html('ok').addClass("success");
		    }
	    });
    };

});