//###################################
// ADVANCED SEARCH
//###################################

    var imgLoaderImage = "/images/sections/loadingAnimations/3894D2_small_white.gif";
    var advancedSearchLoading = false;
    var productTreeChanged = false;
    var productTreeLoaded = false;
    var dataFresh = true; //indicate no search has been performed
    
    imgLoading = new Image();// preload image
    imgLoading.src = imgLoaderImage;
    

     // Detta ska göras när DOM-trädet finns - OnDomReady
    $(document).ready(function(){
	    $("div#search-tabs a").click(slideAdvancedSearchForm);	    
    });

    // Attach dirtyform control to check whether form is changed or not
    function bindFormEvents()
    {
        if(!($("#bind_dirtyform_flag").val() == "true"))
        {
            $("#searchForm").dirty_form();
            $("#bind_dirtyform_flag").val("true");
        }
        
        //Attach events to product tree
       // productTreeEvens();
    }
    
    
    // Load advanced search form
    function loadAdvancedSearch(doReset)
    {
        if($("#searchForm").length == 0)
        {
            if(advancedSearchLoading == false)
            {
                var reset = '';
                if(doReset){
                    reset = '&reset=true';
                }
                else{
                    dataFresh = true;
                }
                
                advancedSearchLoading = true;
                // Show loading animation
                var code =  "<div id='loader' style='position:relative; left:381px; top:100px;'>" +
                                "<img src='/Images/sections/loadingAnimations/Transparent_big_white.gif' />" +
	                        "</div>";
                    $("div#advanced-search").append(code);
                    $("div#advanced-search").attr("style", "display: block;");
                    $("div#advanced-search").addClass("loading");
                
                //To prevent caching. See: http://docs.jquery.com/Ajax/load#urldatacallback
                var rnd = Math.floor(Math.random()*900001)
                
                $("#advanced-search").load("/AdvancedSearch/AdvancedSearchForm.aspx?showsections=companyinfo&rnd="+rnd+""+reset+" #searchForm", function()
                    {  
                       // Inactivate loadinganimation when form is ready
                       $("div#advanced-search").attr("style", "display: none;");
                       $("div#advanced-search").removeClass("loading"); 
                       
                       // Slide down form when loaded
                       $("div#advanced-search").slideDown("slow");
                       
                       advancedSearchLoading = false;
                    }
                );      
            }      
        }
        else{

          $("div#advanced-search").slideDown("slow");
       }
    }
    
    // Show/hide advanced search form
    function slideAdvancedSearchForm()
    {    
        if ($(this).hasClass("advanced-search")) {    		
		    if ($("div#advanced-search").attr('style') == "display: block;") {
			    $("div#search-tabs a.advanced-search").addClass("inactive");
			    $("div#search-tabs a.search").removeClass("inactive");
			    $("div#advanced-search").slideUp("slow");
		    } else {
			    $("div#search-tabs a").removeClass("inactive");
			    $("div#search-tabs a.search").addClass("inactive");
			    
			    //Load advanced search form
			    loadAdvancedSearch(false);
		    }
    		
	    } else {
		    $("div#search-tabs a").removeClass("inactive");
		    $("div#search-tabs a.advanced-search").addClass("inactive");
		    $("div#advanced-search").slideUp("slow");
	    }    
    }

   

    	
    
    
    
    // Return true if form is changed
    function isFormChanged()
    {
        if($("#searchForm").are_dirty() || productTreeChanged) 
        {
            productTreeChanged = false; //check if producttree checkboxes are changed
            return true;
        }
        else
        {
            return false;
        }
    }
    
    //Reset and reload searchform
    function resetAdvancedSearchForm()
    {
        if( $('#freshdata').val() == 'false' ){
            dataFresh = false;
        }
        
        if( dataFresh )
        {
            //Resets all input fields
            clearSection('searchForm'); 
        }
        else
        {
            //Reloads searchform with fresh data
            
            //Slide up
		    $("div#advanced-search").slideUp("slow", function()
		        {
		            //Remove searchform
		           $("#searchForm").remove();
    		       
		           //Reload searchform calling reset
		           loadAdvancedSearch(true);
    		       
		           //Slide down searchform
	               $("div#advanced-search").slideDown("slow");
    	           
	               dataFresh = true;
		        }
		    );
        }
    }
    
    // Clears a section in advanced search form.
    function clearSection(id)
    {
        $('#'+id+' *').each(function(i) {
            var t = this.type, tag = this.tagName.toLowerCase();
            if (t == 'text' || t == 'password' || tag == 'textarea')
                this.value = '';
            else if (t == 'checkbox' || t == 'radio')
                this.checked = false;
            else if (tag == 'select')
                this.selectedIndex = -1;
         });
    }
    
    function slideUpAdvancedSearchSections()
    {
        $("div.section-head").removeClass("visible").next().slideUp();
    }
    
    // Show section after submit
    function slideDownAdvancedSearchSection(obj)
    {    
        if ($(obj).hasClass("visible")) {
	        $(obj).removeClass("visible").next().slideUp();	        
        } else {
	         var id = $(obj).attr("id");
  	         $("#"+id).addClass("visible").slideDown();
        } 
    }
    
    // Show/hide section in advanced search form
    function slideAdvancedSearchSection(obj)
    {
        // använd om vi tycker släpande knappar är ett problem i IE7
        //$("div#advanced-search .section").contents().find("button").hide();        
		if ($(obj).hasClass("visible")) {
			$(obj).removeClass("visible").next().slideUp();
		} else {

		    $(obj).next().children().contents().find("button").hide();
  
		    if($.browser.msie){
		        $("div.section-head").removeClass("visible").next().hide();
			    $("div.section-content").removeClass("visible").next().hide();
		    }
		    else{
		        $("div.section-head").removeClass("visible").next().slideUp();
			    $("div.section-content").removeClass("visible").next().slideUp();
		    }

			$(obj).addClass("visible").next().slideDown().contents().find("button").show();
		}
    }
   
    // Submits advanced search-form with ajax.
    function submitAdvancedSearchForm(obj, getProductTree, getAllProducts)
    {           
        //alert('getProductSection:'+getProductSection+'\n getProductTree:'+getProductTree+'\n getAllProducts:'+getAllProducts);
        
        //Complete tree already loaded?
        if(getProductTree && getAllProducts && productTreeLoaded)
        {
            slideAdvancedSearchSection(obj);
            return false;
        }
        
        if( isFormChanged() || getProductTree )
        {
            productTreeLoaded = false;
            newUrl = '/AdvancedSearch/AdvancedSearchForm.aspx';
            
            //Load producttree?         
            if(getProductTree)
            {
                newUrl += '?showsections=products';
                if(getAllProducts) //Get complete tree
                {
                    newUrl += '&status=getall';
                    productTreeLoaded = true;
                }
            }
            
            // Ajax-options
             var options = { 
                    target:        '#advanced-search',   // target element(s) to be updated with server response       
                    url: newUrl,
                    success:    function() {            
                        slideDownAdvancedSearchSection($(obj).next());
                     },
                     beforeSubmit:    function() {      
                        // Show loadinganimation before submit
                       loadingAnimation($(obj).find("p.intro"), imgLoading.src);
                     }
                }; 
                    
            // Slide up all sections
            slideUpAdvancedSearchSections();
            
            // Retrieve data
            $("#searchForm").ajaxSubmit(options);
            
            //Form reloaded with new data. Set dataFresh false
            dataFresh = false;
         }
         else
         {
            slideAdvancedSearchSection(obj);
         }
         
         return false; 
    }

    //-------------------------------------------------------------------
    // PRODUCTS SECTION
    //-------------------------------------------------------------------
    
    //Attach keypress-event to searchbutton
    $("input#SearchProductsValue")
        .livequery('keypress', function(e) {
            if (e.which == 13) {
                submitAdvancedSearchForm($('#section-products-head'), true, false);
                return false;
            }
            
        });
               
    function textSearchProducts()
    {
        submitAdvancedSearchForm($('#section-products-head'), true, false);
    }
    
    //Check tree-status for all childrens to "node"
    // Checks:
    // - If all childrens are checked: check parent
    // - If some, but not all childrens are checked: highligt parent with bold
    // - If no child is selected: uncheck parent
    // - If parent is selected change name-attribute of all childrens to trash to avoid duplicate filtering
    function recursiveTreeCheck(node)
    {      
        var $child = $(node).children('.child ').eq(0);
        
        if ( $child.attr('class') !== undefined ) //Check if node has children
        {
            var checkboxStatus = 0;
            
            //Reset name-attribute to products
            $child.find('input:checkbox').attr('name', 'products');
            
            $child.children('ul').children('li').each(function(){
            
                
                //For all children do recursive call to myself
                recursiveTreeCheck($(this));
                
                //0 = not initialized
                //1 = all checked
                //2 = all unchecked
                //3 = mixed
                
                // Check status of all childrens (all checked, all unchecked or mixed?)
                $(this).find('h2 input:checkbox,h3 input:checkbox').each(
                     function() {
                         if($(this).is(':checked'))
                        { 
                            if(checkboxStatus == 0) { checkboxStatus = 1; }
                            else if(checkboxStatus == 2) { checkboxStatus = 3; return;}
                        }
                        else{
                            if(checkboxStatus == 0) { checkboxStatus = 2; }
                            else if(checkboxStatus == 1) { checkboxStatus = 3; return; }
                        }
                     }
                   );
            }); 
            
            var $children = $(node).children('.node');
            
            //All Checked - All childrens are checked
            if(checkboxStatus == 1)
            {   
                //alert('allchecked');
                $children.find(':header').css("font-weight", "normal");
                $children.find('input:checkbox').attr('checked', true);

                //All childrens are checked means the parent is checked. 
                //Change name-attribute of all childrens to trash to avoid filtering on both parent and all childrens
                $child.find('input:checkbox').attr('name', 'trash');
            }
            //All unchecked - All childrens are unchecked
            if(checkboxStatus == 2)
            {   
                $children.find(':header').css("font-weight", "normal");
                $children.find('input:checkbox').attr('checked', false);
            }
            
            //Mixed - some childrens are checked some are not
            if(checkboxStatus == 3)
            {
                $children.find(':header').css("font-weight", "bold");
                $children.find('input:checkbox').attr('checked', false);
            } 
            
        }
    }



    //Obs! producttreesearchview. 
    //Attaches click event to all producttree nodes
    //On click set producttree to changed to perform new search
    //Dirty_form doesn't apply to Ajaxloaded productree nodes 
    $("div#producttreesearchview input")
        .livequery('click', function() {
            
	        productTreeChanged = true;
            
	        if($(this).attr('checked'))
	        {
	            //Delete removevalue from hidden checkbox
	            if($(this).next().attr('id') == 'remove_'+$(this).attr('id'))
	            {
	                $(this).next().val("");
	            }
	        }
	        else
	        {
	            //Add removevalue to hidden checkbox
	            if($(this).next().attr('id') == 'remove_'+$(this).attr('id'))
	            {
	                $(this).next().val($(this).val());
	            }   
	        }
	     });
	
	//Obs! producttree -> not producttreesearchview. 
    //Attaches click event to all producttree nodes
    //On click set producttree to changed to perform new search
    //Dirty_form doesn't apply to Ajaxloaded productree nodes 
    $("div#producttree input")
        .livequery('click', function() {
        
	        productTreeChanged = true;
            
	        if($(this).attr('checked'))
	        {
	            //Delete removevalue from hidden checkbox
	            if($(this).next().attr('id') == 'remove_'+$(this).attr('id'))
	            {
	                $(this).next().val("");
	            }
	            
	            //Check all children
	            $(this).closest('li').find('input:checkbox').attr('checked', true);
	        }
	        else
	        {
	            //Add removevalue to hidden checkbox
	            if($(this).next().attr('id') == 'remove_'+$(this).attr('id'))
	            {
	                $(this).next().val($(this).val());
	            }
	            
	            //UnCheck all children
	            $(this).closest('li').find('input:checkbox').attr('checked', false);
	        }
	        
	        //
	        recursiveTreeCheck($(this).closest('.lev1'));	        
	     });
	     	     
	// Get treenode
    $('.producttree .expand')
	    .livequery('click', function() { 
	   
	    // Only load once
	    if($(this).parent().next("div.child").length == 0)
        {
            var id = $(this).next().children("input").attr("id");
            var nodeChecked = '';
            if( id !== undefined )
            {
                var level = id.substring(0,id.indexOf("_"));
                
                var path = $(this).next().children("input").val();
                
                // Display loading animation
                 var code =  "<div id='loader' class='loading'>" +
                                    "<img src='/Images/sections/loadingAnimations/Transparent_big_white.gif' />" +
	                           "</div>";
                 $(".producttree").append(code);
                
                //If node is checked, set checked-flag before retrieving childrens
                if ( $(this).next(':header').children('input:first').is(':checked') ) 
                {
                    nodeChecked = '&check=true';
                }
                
 		        $(this).parent().after("<div class='child' style='display:none;'></div>");
                
                //Load nodes with ajax
                $(this).parent().next("div.child").load("/AdvancedSearch/GetData.aspx?level=" + level + "&path="+ path + nodeChecked +" #data ul", function()
                    {   
                        // Inactivate loadinganimation when form is ready
                        $(this).prev().children("div.expand").addClass("active");
                        $(this).show();
                        $(".loading").attr("style", "display: none;");
                    }); 
              }
        }
        else
        {
            // Show/hide already loaded nodes
            if ($(this).hasClass('active')) {
		        $(this).removeClass("active");
		        $(this).parent().next("div.child").hide();
		        
             } else {
                $(this).addClass("active");
                $(this).parent().next("div.child").show();
             }
        }
	});
    
    
    //-------------------------------------------------------------------
    // GEOGRAPHY SECTION
    //-------------------------------------------------------------------
    // Enable/disable geography filters
    function enableGeographyFilterCheckBox(listbox, checkbox)
    {
        if($("#"+listbox).val() != null)
            $("#"+checkbox).removeAttr("disabled");
        else
            $("#"+checkbox).attr("disabled", "disabled");
    }
    
    // Submits advanced search-form with ajax.
    // Includes special option for geography search
    function submitAdvancedSearchFormGeography(filter)
    {      
       
        var imgSrc = "/images/sections/loadingAnimations/60A9DB_small_white.gif";
        imgLoad = new Image();// preload image
        imgLoad.src = imgSrc;
        
        newUrl = '/AdvancedSearch/AdvancedSearchForm.aspx?showsections=geography';
        
        // Ajax-options
         var options = { 
                target:        '#advanced-search',   // target element(s) to be updated with server response       
                url: newUrl,
                success:    function() {         
                    slideDownAdvancedSearchSection('#section-geography-content');
                 },
                 beforeSubmit:    function() {      
                    // Show loadinganimation before submit
                    if(filter == "FilterCountries")
                        loadingAnimation($("#countries .header"), imgLoad.src);
                    else if(filter == "FilterCounties")    
                        loadingAnimation($("#counties .header"), imgLoad.src);
                    else if(filter == "FilterCities")
                        loadingAnimation($("#cities .header"), imgLoad.src);
                 }
            }; 
        
        // Retrieve data
        $("#searchForm").ajaxSubmit(options);
        
         //Form reloaded with new data. Set dataFresh false
         dataFresh = false;
            
         return false; 
    }

    //--------------------------------------------------------------
    //Free text search for geography
    //--------------------------------------------------------------
    
    //Unchecks alla geography selection. 
    //Used when a text-search is performed to prevent earlier selections to be included in the search.
    function unCheckGeograpfySelections()
    {
         $('#SelectCities :selected').attr("selected", false);
         $('#SelectCounties :selected').attr("selected", false);
         $('#SelectCountries :selected').attr("selected", false);
         $('#FilterCities').attr("checked", false);
         $('#FilterCounties').attr("checked", false);
         $('#FilterCountries').attr("checked", false);
    }

    // Textsearch for locations
    function textSearchGeography()
    {   
        unCheckGeograpfySelections();
        submitAdvancedSearchFormGeography();
    }
    
    
    //Submit form on keypress
    function searchGegraphyKeyPress(e)
    {
        var keynum;
        
        if(window.event) // IE
          {
          keynum = e.keyCode;
          }
        else if(e.which) // Netscape/Firefox/Opera
          {
          keynum = e.which;
          }

        
        if (keynum == 13) 
        {
            unCheckGeograpfySelections();
            submitAdvancedSearchFormGeography();
            //loadGeografiSection("search", $("#SearchLocationValue").val());
            return false;
        } 
        else
        {
            return keynum;
        }
    }

    // loading animation
    function loadingAnimation(section, imgSource)
    {
        if($("#loading").length == 0)
        {
            var code = "<img src=" + imgSource  + " alt='loading' class='loadanimation' id='loadingAnimation' />";
            section.append(code);
            return code;
        }
        return null;
    }
    
    // remove loading animation if exists
    function inactivateLoadingAnimation()
    {
        if($("#loadingAnimation").length > 0)
        {
            $("#loadingAnimation").remove();
        }
    }