﻿/// <reference path="jquery-1.2.6.min-vsdoc.js" />
/// <reference path="shadowbox-2.0.js" />

var Json = {

    Get : function(jsonStr)
    {
        return eval('(' + jsonStr + ')');
    }
}

var Preloader = {

    Show : function(preloaderImage)
    {
        if($(preloaderImage))
        {
            $(preloaderImage).css("display", "block");
        }
    },
    
    Hide : function(preloaderImage)
    {
        if ($(preloaderImage)) 
        {
            $(preloaderImage).css("display", "none");
        }
    }
}

/*
 * Description   : Used for dynamic showing FAQitems
 * Author       : Anton dot Kallenberg at Softronic dot se
 * Dependencies : Jquery-1.2.6, FAQService.GetFAQItems()
 */
var FAQ = {
    
    IsPopulated : [],
    ItemContainer : undefined,
    CategoryContainer : undefined,
    CategoryId : -1,
    OutGooingRequest : null,

    Main : function ()
    {
        var topElement = undefined;
        var categoryId = -1;
        
        $("div[@class='FAQCategory']").find("div:first")
                                      .find("div:first")
                                      .find("a:first")
                                      .bind("click", function(e)
        {
            //dont change ID || CategoryContainer if -> 
            //request is outgoing
            if(FAQ.OutGooingRequest == null)
            {
                topElement = $(this).parent().parent().parent();
                categoryId = topElement.attr("id").split("_")[1];
                
                FAQ.CategoryContainer = topElement;
                FAQ.CategoryId = categoryId;
            }
            
            FAQ.GetCategoryItems();
        });
    },

    GetCategoryItems : function()
    {
        FAQ.ItemContainer = $(FAQ.CategoryContainer).find("div[@class='FAQItemContainer']");
        
        if($(FAQ.ItemContainer).css("display") == "block")
        {
            $(FAQ.ItemContainer).hide("fast");
            $(FAQ.CategoryContainer).find("div:first")
                                    .find("div:first")
                                    .find("a:first").attr("id","");
            return;
        }
        else
        {
            // If server has been called for current categoryItems
            // -> dont ask again just show already rendered HTML
            if(FAQ.IsPopulated.join("|").indexOf(FAQ.CategoryId) != -1)
            {
                $(FAQ.ItemContainer).show("fast");
                $(FAQ.CategoryContainer).find("div:first")
                                        .find("div:first")
                                        .find("a:first").attr("id","faqCategoryActive");
                return;
            }
            
            if(FAQ.OutGooingRequest == null)
            {
                // Call WS for categoryItems
                Preloader.Show($("img[id='FAQPreloader']"));
                var jsonRequest = "{'CategoryId' : '" + FAQ.CategoryId + "'}";   
                FAQ.OutGooingRequest = $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "/Services/FAQService.asmx/GetFAQItems",
                    data: jsonRequest,
                    dataType: "json",
                    success: function(response) {
                        FAQ.RenderFAQItems(response.d);
                        FAQ.OutGooingRequest = null;
                        Preloader.Hide($("img[id='FAQPreloader']"));
                    }   
                });
                
                setTimeout(function(){
                  // If the request is still running after 10 sec ->
                  // abort it.
                  if (FAQ.OutGooingRequest != null)
                  { 
                    FAQ.OutGooingRequest.abort();
                    FAQ.OutGooingRequest = null;
                    Preloader.Hide($("img[id='FAQPreloader']"));
                  }
                }, 10000);
            }
        }
    },
    
    BindFAQItemsEvents : function()
    {
        // Go from CategoryContainer root -> 
        // we just want to add "click" event one time.
        $(FAQ.CategoryContainer).find("div[@class='FAQItemContainer']")
                                .find("div[@class='FAQItem']")
                                .find("div:first")
                                .find("a:first")
                                .bind("click", function(e)
        {
            var FAQItemBody = $(this).parent().parent().find("div[@class='FAQItemBody']");
            
            if($(FAQItemBody).css("display") == "block")
            {
                $(FAQItemBody).hide("fast");
                $(this).attr("id","");
            }
            else
            {
                $(FAQItemBody).show("fast");
                $(this).attr("id","faqItemActive");
            }
        });
    },
    
    RenderFAQItems : function(FAQItems)
    {
        $(FAQ.CategoryContainer).find("div:first")
                                .find("div:first")
                                .find("a:first").attr("id","faqCategoryActive");
                                    
        var html = "";
        for(var i = 0; i < FAQItems.length; i++)
        {
            html += '  <div class="FAQItem">';
            html += '     <div class="FAQItemHeading">';
            html += '       <a href="javascript:void(0)">' + FAQItems[i].Header  + '</a>';
            html += '    </div>';
            html += '    <div class="FAQItemBody" style="display: none;">' ;
            html += '     <p>' + FAQItems[i].MainText + '</p>';
            html += '    </div>';
            html += '  </div>';
        }
        
        $(FAQ.ItemContainer).html(html);
        
        FAQ.BindFAQItemsEvents();
        
        $(FAQ.ItemContainer).css("display","none");
        $(FAQ.ItemContainer).show("fast");
        
        //add current item to IsPopulated array
        FAQ.IsPopulated.push(FAQ.CategoryId);
    }
}

/*
 * Description   : Used for dynamic showing Dropdown menus
 * Author       : Anton dot Kallenberg at Softronic dot se
 * Dependencies : Jquery-1.2.6
 */
Dropdowns = {
    Create : function()
    {
        $("ul[@class='dropDownMenu']").find("li[@class='top gotChildren']").hover(
            function(e) 
            { 
                if($(this).find("ul:animated").length <= 0) 
                {
                    $(this).find("a:first").attr("class", "top gotChildren gotChildrenSelected");
                    //$(this).find("ul:first").show("fast");
                    $(this).find("ul:first").animate({ height: 'show' }, 'fast', null, null);
                    
                }
            },
            function(e) 
            { 
                $(this).find("a:first").attr("class","top gotChildren");
                //$(this).find("ul:first").hide("fast");
                $(this).find("ul:first").animate({ opacity: 'hide' }, 'fast', null, null);
            }
        );
    }
}


LeftMenuList =
{
    Remove: function()
    {
        $("ul[@class='leftMenu']").find("li[@class='removeFromList']").each(function() {
            $(this).remove();
        });
    }
}


MailtoLinks = {
    Create : function()
    {
        $("a[@href*=@byggnads.se]").each(function() {
			$(this).attr("href", "/Ovrigt/Maila-till-Byggnads/?mailto=" + $(this).attr('href').substring(7));
		} );
    }
}


RightMenu = {
    FixLastItem : function()
    {
        $("ul[@id='rightMenu']").find("li:last").attr("class", "rightMenuLastItem");
    },

    Remove: function()
    {
        $("ul[@id='rightMenu']").find("li[@class='removeFromList']").each(function() {
            $(this).remove();
        });
    }
}


PopularSearches = {
    
    OutGooingRequest : null,
    
    Main : function()
    {
        $("a[@id='popularSearches']").hover(
            
            //over
            function(e)
            {
                if(PopularSearches.OutGooingRequest == null)
                {
                    var jsonRequest = "{}";   
                    PopularSearches.OutGooingRequest = $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/Services/SearchService.asmx/MostPopular",
                        data: jsonRequest,
                        dataType: "json",
                        success: function(response) {
                          PopularSearches.OutGooingRequest = null;
                          PopularSearches.RenderSearchItems(response);
                        }   
                    });
                    
                    setTimeout(function(){
                      // If the request is still running after 10 sec ->
                      // abort it.
                      if (FAQ.OutGooingRequest != null)
                      { 
                        PopularSearches.OutGooingRequest.abort();
                        PopularSearches.OutGooingRequest = null;
                      }
                    }, 10000);
                }
            },
            
            //out
            function(e){
                PopularSearches.OutGooingRequest.abort();
                PopularSearches.OutGooingRequest = null;
            }
        );
    },
    
    RenderSearchItems : function()
    {
        var html = "";
        
    }
}

Print = {

    ShowDialog : function()
    {
        if (window.print) 
        {
            $("*[@class='triggerPrint']").bind("click", function(e)
            {
                window.print();
            });
        }
    }
}

Redirect = {

    Add : function(elm, url)
    {
        $(elm).bind("click", function(e)
        {
            window.location = url;
        });
    }
}

Watermark = {

    SetWatermark : function()
    {
        swapValues=[];
        $(".watermark").each(
            function(i){
                swapValues[i]=$(this).val();
                $(this).focus(function()
                    {
                        if($(this).val()==swapValues[i])
                        {
                            $(this).val("")
                        }
                    }
                ).blur(function()
                    {
                        if($.trim($(this).val())=="")
                            {
                                $(this).val(swapValues[i])
                            }
                     }
                 )
            }
       )
    }
}

Shadowbox.loadSkin('byggnads', '/ClientUI/js/skin/');
Shadowbox.loadLanguage('sv', '/ClientUI/js/lang/');
Shadowbox.loadPlayer(['flv', 'html', 'iframe', 'img', 'qt', 'swf', 'wmp', 'ascx'], '/ClientUI/js/player/');

$(document).ready(function() {
    FAQ.Main();
    Dropdowns.Create();
    RightMenu.Remove();
    RightMenu.FixLastItem(); //Must be called after RightMenu.Remove()
    Print.ShowDialog();
    Watermark.SetWatermark();

    Redirect.Add("div[@id='logo']", "/");

    var options = {
        resizeLgImages: true,
        displayNav: true,
        handleUnsupported: 'remove',
        keysClose: ['c', 27] // c or esc
    };

    Shadowbox.init(options);

    // open a welcome message
//    Shadowbox.open({
//        player: 'html',
//        title: 'Welcome',
//        content: '<div id="welcome-msg">Welcome to my website!</div>',
//        height: 350,
//        width: 350
//    });

});
