// JavaScript/JQuery Functions Document

//Handle Home Page Product Icons if no flash
function writeSavingsProductIcon()
{
    document.write('<p class="product-logo"><img src="images/iconLarge-savings.png" alt="Piggy bank - savings &amp; investments" width="102" height="158" /></p>');
}

function writeMortgageProductIcon()
{
    document.write('<p class="product-logo"><img src="images/iconLarge-mortgages.png" alt="House - mortgages" width="102" height="158" /></p>');
}

function writeInsuranceProductIcon()
{
    document.write('<p class="product-logo"><img src="images/iconLarge-insurance.png" alt="Umbrella - insurance &amp; protection" width="102" height="158" /></p>');
}

function writePensionProductIcon()
{
    document.write('<p class="product-logo"><img src="images/iconLarge-pensions.png" alt="Nest egg - pensions" width="102" height="158" /></p>');
}

//////////////////////////////////////////////////////////////////////
////Homepage Explore Products Div Toggle                          ////
////Added by DBrennan 16/10/09                                    ////
////JQuery function to toggle div and swap helper arrow image     ////
//////////////////////////////////////////////////////////////////////

function initExploreProductInsert()
{

    animatedcollapse.addDiv('div-toggle', 'fade=1,speed=250,hide=1,persist=1');
    animatedcollapse.init();
    animatedcollapse.ontoggle = function($, divobj, state)
    {
        if (divobj.id == "div-toggle")
        { //if DIV is being toggled
            if (state == "block") //if div is expanded
                $("#toggle-image").attr({ src: "cssImages/helper_bullet_down.gif" });
            else
                $("#toggle-image").attr({ src: "cssImages/helper_bullet.gif" });
        }
    }
}


// Makes product feature boxes on home page same height
$(function()
{
    var headerBiggest = 0;
    //    $(".product-features > div > div > h2 ").each( function() {
    //        if( $(this).height() > headerBiggest ) headerBiggest = $(this).height();
    //    }).height(headerBiggest);
    //    
    //    $(".product-features > div > div > h2 ").each( function() {
    //        $(this).height(headerBiggest);
    //    });	

    var biggest = 0;
    $(".product-features > div > div").each(function()
    {
        if ($(this).height() > biggest) biggest = $(this).height();
    }).height(biggest);

    $(".product-features > div > div").each(function()
    {
        $(this).height(biggest);
    });
});

var viewNearest = "";

function swapSubMenu(img)
{
    var el = document.getElementById(img);
    if (el)
    {
        if (el.style.display == "none")
            el.style.display = "block";
        else
            el.style.display = "none";
    }
}

function setViewNearest(nearest)
{
    viewNearest = nearest;
}

$(function()
{
    $("#viewMoreBranch").click(function()
    {
        var buttonText = $("#viewMoreBranch").eq(0).text();
        if (buttonText == "View More")
        {
            $(this).parent().find(".hidden").each(function()
            {
                $(this).removeClass("hidden");
            });
            $("#viewMoreBranch").eq(0).text("View Nearest");
            return false;
        }
        else
        {
            var count = 0;
            $(".branches table tr").each(function()
            {

                if (count > 5)
                {
                    $(this).addClass("hidden");
                }
                count++;
            });
            $("#viewMoreBranch").eq(0).text("View More");
            return false;
        }
    });

    $("#viewMoreAgent").click(function()
    {
        var agentText = $(this).text();
        if (agentText == "View More")
        {
            $(this).parent().find(".hidden").each(function()
            {
                $(this).removeClass("hidden");
            });
            $("#viewMoreAgent").eq(0).text("View Nearest");
            return false;
        }
        else
        {
            var agentCount = 0;
            $(".agents table tr").each(function()
            {

                if (agentCount > 5)
                {
                    $(this).addClass("hidden");
                }
                agentCount++;
            });
            $("#viewMoreAgent").eq(0).text("View More");
            return false;
        }
    });

});

//// Header text fields - managing default values

$(function()
{

    var searchVal = "search for...";
    var newsVal = "Your email address";
    var findVal = "Postcode";

    // Site search
    $(".site-search input").each(function()
    {
        createText(searchVal, $(this));
    });

    $(".site-search input").focus(function()
    {
        removeText(searchVal, $(this));
    });

    $(".site-search input").blur(function()
    {
        restoreText(searchVal, $(this));
    });

    // Newsletter signup
    $(".news-signup input").each(function()
    {
        createText(newsVal, $(this));
    });

    $(".news-signup input").focus(function()
    {
        removeText(newsVal, $(this));
    });

    $(".news-signup input").blur(function()
    {
        restoreText(newsVal, $(this));
    });

    // Branch-finder search
    $(".branch-finder input").each(function()
    {
        createText(findVal, $(this));
    });

    $(".branch-finder input").focus(function()
    {
        removeText(findVal, $(this));
    });

    $(".branch-finder input").blur(function()
    {
        restoreText(findVal, $(this));
    });
});


// Create default text for text field on page load
function createText(defVal, thisObj)
{

    var inpType = thisObj.attr("type");
    if (inpType != "submit")
    {
        thisObj.attr("value", defVal);
    }
}

// Remove default text on focus. Ignore user-inserted text
function removeText(defVal, thisObj)
{
    var inpType = thisObj.attr("type");
    if (inpType != "submit")
    {
        var currVal = thisObj.attr("value");
        if (currVal == defVal) { thisObj.attr("value", ""); }
    }
}

// Restore default text on focus. Ignore user-inserted text
function restoreText(defVal, thisObj)
{

    var inpType = thisObj.attr("type");
    if (inpType != "submit")
    {
        var currVal = thisObj.attr("value");
        if (currVal != "" && currVal != defVal)
        {
            thisObj.attr("value", defVal);
            thisObj.attr("value", currVal);
        } else { $(this).attr("value", defVal); }
    }
}




////////////////////////
//// Product Finder ////
////////////////////////

/* 

Initial Setup
-------------

If non-javascript option is simple links to product sections (icons) and product A-Z (action link), will need to replace all this with new HTML.

*/
var productSearch = "";
var productGuideIsOpen = false;

function setSearch(group)
{
    productSearch = group;
}


var activeImages = ["picon_savings.gif", "picon_mortgage.gif", "picon_insure.gif", "picon_pensions.gif"];
var greyImages = ["picon_savings_ro.gif", "picon_mortgage_ro.gif", "picon_insure_ro.gif", "picon_pensions_ro.gif"];
var imagePath = "/images/";
var pfState = "";
var currActive = -1;
var showLink = false;

$(function()
{
    // variable to hold image path *** Will probably need updating in .NET solution ***   

    // holds questions generated from XML file
    //var questions = new Array();

    // Arrays to hold file names for active and inactive icon images

    var qGroup = ".questions #" + productSearch;

    if (productSearch != "")
    {

        var qGroup = ".questions #" + productSearch;
        $(".questions #mortgage").eq(0).hide().removeClass("current");
        $(".questions #savings").eq(0).hide().removeClass("current");
        $(".questions #insurance").eq(0).hide().removeClass("current");
        $(".questions #pensions").eq(0).hide().removeClass("current");

        $(qGroup).eq(0).show().addClass("current");

        var children = $(".product-chooser .components .products").children();

        setButtons(children, productSearch, pfState, productSearch);

        productSearch = "";
    }

    else
    {
        $(".product-chooser .components .questions").eq(0).hide();
    }

    // When icon is clicked
    $(".product-chooser .components .products a").click(function()
    {
        pfState = "opening";

        var thisLink = $(this).attr("class");
        var children = $(".product-chooser .components .products").children();

        setButtons(children, thisLink, pfState, thisLink);

        //	children.each(function(e){
        //		// If current icon matches clicked icon
        //		if ($(this).attr("class") == thisLink) {
        //			var actImage = activeImages[e];
        //			var imgPath = imagePath + actImage;
        //			$(this).children().each(function(){ $(this).attr("src",imgPath)});

        //			// If clicked icon is currently open section close Product Finder and reset icons 
        //			if (thisLink == currActive){
        //                $(".product-chooser .components .questions").each(function() { $(this).toggle() });

        //                $(".product-chooser .components .products").children().each(function(g){

        //			        var actImage = activeImages[g];
        //			        var imgPath = imagePath + actImage;
        //			        $(this).children().each(function(){ $(this).attr("src",imgPath)});
        //			        
        //			        //set flag to determine if onclick event should be fired
        //			        //NB: refactor as required but ensure event is not fired IF product guide is closed			        
        //                    productGuideIsOpen = false;
        //                    
        //			        pfState = "closing";
        //			        currActive = -1;
        //                });
        //			} 
        //			else {

        //			    $(".product-chooser .components .questions").each(function() { $(this).hide() });

        //			    //$(".product-chooser .components .questions")[0].innerHTML = questions[e];
        //			    showLink = showProductGuide(thisLink);
        //			    
        //			    //set flag to determine if onclick event should be fired
        //			    //NB: refactor as required but ensure event is only fired IF product guide is open
        //			    productGuideIsOpen = true;
        //			    
        //			    //show/hide 'search products, 'reset', and 'go' buttons as required
        //			    //NB: refactor as required but ensure functionality remains
        //			    if (thisLink != 'mortgage')
        //			    {
        //                    document.getElementById("mortgageInputs").className ='hidden';
        //                    document.getElementById("actionReset").className ='hidden';
        //                    document.getElementById("actionGo").className ='hidden';
        //                    document.getElementById("mainQuestion").className ='';
        //                    document.getElementById("secondaryQuestions").className ='';                    
        //                    document.getElementById("actionSearch").className ='';			    
        //			        
        //			    }

        //			    $(".product-chooser .components .questions").each(function() { $(this).show() });
        //			    currActive = thisLink;
        //			}
        //		}	
        //		// If current icon does not match clicked icon
        //		else {
        //		    if (pfState == "closing"){ }
        //		    else {
        //			    var greyImage = greyImages[e];
        //			    var imgPath = imagePath + greyImage;
        //			    $(this).children().each(function(){ $(this).attr("src",imgPath)});
        //			}
        //		}
        //	});
        // Deactivates link
        return showLink;
    });
});


//Function to open the correct Product Guide questions according to Product Type
//Added by DBrennan 26/10/09

$(function()
{
    if (!document.getElementById) return;

    if (!document.getElementById("ctl00_cphMain_productType")) return;

    var thisLink = (document.getElementById("ctl00_cphMain_productType").value);
    var thisLink = thisLink.toLowerCase();
    var children = $(".product-chooser .components .products").children();

    setButtons(children, thisLink, pfState, thisLink);
    return showLink;

});


function showProductGuide(productType)
{
    $(".questions #mortgage").eq(0).hide().removeClass("current");
    $(".questions #savings").eq(0).hide().removeClass("current");
    $(".questions #insurance").eq(0).hide().removeClass("current");
    $(".questions #pensions").eq(0).hide().removeClass("current");

    if (document.getElementById(productType) != null)
    {
        var currentProd = ".questions #" + productType;

        $(currentProd).show();

        var secQs = currentProd + " #secondaryQuestions";

        // Hide secondary question container if no questions
        if ($(secQs).children("h4").length == 0)
        {
            $(secQs).hide();
        }

        // Added by DBrennan 28/06/2010 Removal of Secondary Mortgage Questions
        if (productType == 'mortgage')
        {
            $("#secondarymortgageQuestion1").hide();
        }

        document.getElementById("guideType").value = productType;
        return false;
    }
    else return false;
}

/////////////////////////////////////////////////////////////////////////////////////
//First level Questions MUST come from Ektron (with associated taxonomy items)
//NB: Refactor as required but ensure content comes from XML server control via Ektron
/////////////////////////////////////////////////////////////////////////////////////

// show/hide on category/product details table
$(function()
{
    $(".all-categories .category a.prod-link").click(function()
    {
        // class to change background image bullet
        $(this).toggleClass("open");
        $(this).parent().next().each(function()
        {
            $(this).toggle();
        });
    });
});

//// show/hide on category/product details table
$(function()
{
    $(".category .cat-link a").click(function()
    {
        // class to change background image bullet
        $(this).toggleClass("open");
        $(this).parent().next().each(function()
        {
            $(this).toggle();
        });
    });
});


var checkCounter = 0;

//function SubmitComparatorForm()
//{

//    if(!document.getElementById) return;

//    if(checkCounter == 0) 
//    {
//        alert("Please select at least 1 product.");
//        return;
//    }

//    if(document.getElementById("ctl00_cphMain_productType").value=="mortgage")
//    {
//        document.getElementById("aspnetForm").action = "/cms400min/mortgages/compare-products.aspx";
//    }
//    else
//    {
//        document.getElementById("aspnetForm").action = "/cms400min/savings/compare-savings.aspx";
//    }
//    
//    document.getElementById("aspnetForm").submit();
//}

function SubmitProductGuideForm(rootPath)
{
    if (!document.getElementById) return;

    if (productGuideIsOpen == true)
    {
        if (document.getElementById("mortgage") || document.getElementById("savings"))
        {
            //if mortgage calc inputs are hidden, just submit the form
            //            if (document.getElementById("mortgageInputs").className =='hidden')
            //            {
            document.getElementById("ctl00_currentPage").value = 1;
            document.getElementById("aspnetForm").action = rootPath + "guide-search-results.aspx";
            document.getElementById("aspnetForm").submit();
            //            }
            //            else // else hide them and show the questions instead
            //            {
            //                showGuideQuestions();
            //            }

        }
    }
}


var checkCallServer = new Array();
var checkCallServerAZ = new Array();


// Gets product info from server only after checking that this content hasn't already been retrieved.
function getProducts(category_id)
{

    var found = false;
    $(checkCallServer).each(function(e)
    {
        if ($(checkCallServer)[e] == category_id)
        {
            found = true;
        }
    });
    if (found == true) { }
    else
    {
        checkCallServer[checkCallServer.length] = category_id;
        CallPServer(category_id);
    }
}

// Gets product info (for Product A-Z) from server only after checking that this content hasn't already been retrieved.
function getProductsAZ(category_id, status)
{
    var found = false;
    $(checkCallServerAZ).each(function(e)
    {
        if ($(checkCallServerAZ)[e] == category_id + "|" + status)
        {
            found = true;
        }
    });
    if (found == true) { }
    else
    {
        checkCallServerAZ[checkCallServerAZ.length] = category_id + "|" + status;
        CallAZServer(category_id + "|" + status, "");
    }
}

function ReceiveAZServerData(rValue)
{
    //complex split here as the second element may include multiple control chars
    //but hopefully not our control of '%|%'
    var spanID = rValue.split("%|%")[0];
    var status = rValue.split("%|%")[1];
    var sHTML = rValue.split("%|%")[2];

    document.getElementById("category_products_" + spanID + status).innerHTML = sHTML;
    document.getElementById("category_products_" + spanID + status).className = "";
}

function ReceivePServerData(rValue)
{
    //complex split here as the second element may include multiple control chars
    //but hopefully not our control of '%|%'
    var spanID = rValue.split("%|%")[0];
    var sHTML = rValue.split("%|%")[1];

    document.getElementById("category_products_" + spanID).innerHTML = sHTML;
    document.getElementById("category_products_" + spanID).className = "";
}


// Site Map //

$(function()
{
    //alert($("#site-map > ul").length);
    $("#site-map > ul > li").css("float", "right");
    $("#site-map > ul > li").css("width", "50%");
    $("#site-map > ul > li:first-child").css("float", "left");
    $("#site-map > ul ").eq(1).css("display", "none");
});

// Empty the product guide fields...
function ClearProductGuide()
{
    if (!document.getElementById) return;

    document.getElementById("propertyAmount").value = "";
    document.getElementById("borrowAmount").value = "";
}

function isInteger(s)
{
    var i;

    if (isEmpty(s))
        if (isInteger.arguments.length == 1) return 0;
    else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    return true;
}

function isEmpty(s)
{
    return ((s == null) || (s.length == 0))
}

function isDigit(c)
{
    return ((c >= "0") && (c <= "9"))
}

function setButtons(buttons, clickedButton, state, thisLink)
{
    buttons.each(function(e)
    {
        // If current icon matches clicked icon
        if ($(this).attr("class") == clickedButton)
        {

            var actImage = activeImages[e];
            var imgPath = imagePath + actImage;
            $(this).children().each(function() { $(this).attr("src", imgPath) });

            // If clicked icon is currently open section close Product Finder and reset icons 
            if (thisLink == currActive)
            {

                $(".product-chooser .components .questions").each(function() { $(this).toggle() });

                $(".product-chooser .components .products").children().each(function(g)
                {

                    var actImage = activeImages[g];
                    var imgPath = imagePath + actImage;
                    $(this).children().each(function() { $(this).attr("src", imgPath) });

                    //set flag to determine if onclick event should be fired
                    //NB: refactor as required but ensure event is not fired IF product guide is closed			        
                    productGuideIsOpen = false;

                    state = "closing";
                    currActive = -1;
                });
            }
            else
            {

                $(".product-chooser .components .questions").each(function() { $(this).hide() });

                //$(".product-chooser .components .questions")[0].innerHTML = questions[e];
                showLink = showProductGuide(thisLink);

                //set flag to determine if onclick event should be fired
                //NB: refactor as required but ensure event is only fired IF product guide is open
                productGuideIsOpen = true;

                //show/hide 'search products, 'reset', and 'go' buttons as required
                //NB: refactor as required but ensure functionality remains

                document.getElementById("mainQuestion-" + thisLink).className = '';
                document.getElementById("actionSearch").className = '';

                if (thisLink == "mortgage")
                {
                    //Commented out by DBrennan 28/06/2010 Removal of Mortgage Calculator
                    //document.getElementById("secondaryQuestion-mortgage-select1").className = '';

                    if (document.location.href.toUpperCase().search("COMPARE-PRODUCTS.ASPX") != -1)
                    {
                    //Modified by DBrennan 28/06/2010 - Removal of Mortgage Calculator
                    document.getElementById("mortgageInputs").className = 'hidden';
                    document.getElementById("actionReset").className = 'hidden';
                    document.getElementById("actionGo").className = 'hidden';
                                       
                    //    document.getElementById("mortgageInputs").className = '';
                    //    document.getElementById("actionReset").className = 'reset';
                    //    document.getElementById("actionGo").className = 'go';
                    }
                }
                else if (thisLink == "savings")
                {
                    document.getElementById("secondaryQuestion-savings-select1").className = '';
                    document.getElementById("secondaryQuestion-savings-select2").className = '';
                    document.getElementById("secondaryQuestion-savings-select3").className = '';
                    document.getElementById("mortgageInputs").className = 'hidden';
                    document.getElementById("actionReset").className = 'hidden';
                    document.getElementById("actionGo").className = 'hidden';
                }
                else if (thisLink == "pensions")
                {
                }
                else if (thisLink == "insurance")
                {
                }

                $(".product-chooser .components .questions").each(function() { $(this).show() });
                currActive = thisLink;
            }
        }
        // If current icon does not match clicked icon
        else
        {
            if (state == "closing") { }
            else
            {
                var greyImage = greyImages[e];
                var imgPath = imagePath + greyImage;
                $(this).children().each(function() { $(this).attr("src", imgPath) });
            }
        }
    });
}
