// JavaScript Document
var searchNavFor;
$(document).ready(function () {
    //Load in blog feed
    if($('#blogFeed').length > 0){
        $('#blogFeed').rssfeed22('http://blog.myfinances.co.uk/feeds/posts/default', {
            header: false,
            titletag: 'h3',
            limit: 3
        });
    }

    //Show fb or disqus comment count
    if ($("#fb-comments").length > 0) {
        $("#facebookComments").css("display", "block");
    } else {
        $("#discussComments").css("display", "block");
    }

    //preload images for article rotator
    if($('.image_thumb').length > 0){
        var hrefs = new Array();
        $('.image_thumb li img').each(function () {
            hrefs.push($(this).attr('src'));
        })
        $.imgpreload(hrefs, function () { });
    }
    
    $(".az-ajax li a").click(function(){
        filter = $(this).attr('rel');

        $(".AZ li a").each(function(indexaz){
            $(this).removeClass('az-selected');
        });

        $(this).addClass('az-selected');

        AJAXCompanyAZList(filter, "#company_listing");
        return false;
    });

    //CompOnOff();

    navRoundCorners();
    CompareTableFilter();
    ShowOnePartner();

    $("#shift tr").each(function (index2) {
        this.style.display = "none";
    });

    $(".xLink").click(function () {
        window.open($(this).attr("href"), "_blank");
        return false;
    });

    //for partners in right column
    Rotator();

    //track links leaving the site
    $('a.outbound').click(function () {
        var $a = $(this);
        var href = $a.attr('href');
        var category = 'outbound'; // set this to whatever you want
        var event = 'click'; // set this to whatever you want
        var label = href; // set this to whatever you want
        _gaq.push(['_trackEvent', category, event, href]);
        setTimeout('document.location = "' + href + '"', 200);
    });

    //highlight sub section
    primarySections = new Array("mortgages", "insurance", "savings", "investments", "pensions", "loans-and-credit", "cut-your-bills", "tag");
    urlSegments = window.location.pathname.split("/");
    url = "";

    if (urlSegments.length == 2) {
        url = (arrayTestForValue(urlSegments[1], primarySections)) ? "" : window.location.pathname;
    } else if (urlSegments.length >= 3) {
        url = window.location.pathname;
    }

    if (url != "") {
        //alert(sectionOne);
        $("#subNavigation a").each(function (index) {
            //alert($(this).attr("href").indexOf(searchNavFor));
            element = $(this);
            hrefText = element.attr("href");
            //alert(hrefText +" = "+  url);
            if (hrefText == url) {
                element.addClass("subNavHighlight");
            }
        });
    }

    setInterval(shimmer, 4000);
    //#newsletterSignup
    $(".newsletterSignupBtn").click(function () {
        var emailForm = $("#newsletterSignup");
        valid = true;
        emailadd = $("#news-emailAddress").val();
        name = $("#news-name").val();
        //validate email
        if(!checkEmail(emailadd)){
            $("#feedbackMsg").html("Email is incorrect.")
                        .addClass("newsError");
            valid = false;
        }
        //validate name
        if(name == "" || name == " "){
            $("#feedbackMsg").html("Name is required.")
                        .addClass("newsError");
            valid = false;
        }

        if(valid){
            $.ajax({
                url: "/Newsletters/AddSubscriber",
                type: "POST",
                data: $(emailForm).serialize(),
                success: function(data){
                    //set in CSS errorMsg to display:none
                    if(data.indexOf("Success") != -1){
                        $("#feedbackMsg").removeClass();
                        $("#feedbackMsg").html("<h3>Thank you for subscribing.</h3>"+
                                    "<p>Please check your email and click the confirm link. (Check your spam box if it does not appear in your inbox.)</p>")
                                    .addClass("newsSuccess")
                                    .show(1000);
                        $('#subscriptionform').slideUp(500);
                        $('.add-signupsocial').slideDown(500);
                    }else{
                        $("#feedbackMsg").removeClass();
                        $("#feedbackMsg").html("<h3>Failed to add you.</h3><p>"+data+"</p>")
                                    .addClass("newsError")
                                    .show(1000);
                    }
                },
            });
        }else{
            $("#feedbackMsg").show(1000);
        }
        return false;
    });

    /* newsletter handlers */
    $('#sign-up, .addionalSite').click(function (e) {
        $('#newsletter-subscription').modal({
            minHeight: 485,
            overlayClose: true,
            zIndex: 9999999,
            onOpen: function (dialog) {
                dialog.overlay.fadeIn('slow', function () {
                    dialog.container.slideDown('slow', function () {
                        dialog.data.fadeIn('slow');
                        var $a = $('.topSocial #sign-up');
                        var href = $a.attr('href');
                        var category = 'Newsletter View'; // set this to whatever you want
                        var event = 'click'; // set this to whatever you want
                        var label = href; // set this to whatever you want
                        _gaq.push(['_trackEvent', category, event, href]);
                    });
                });
            },
            onClose: function (dialog) {
                dialog.data.fadeOut('slow', function () {
                    dialog.container.slideUp('slow', function () {
                        dialog.overlay.fadeOut('slow', function () {
                            $.modal.close(); // must call this!
                        });
                    });
                });
            }
        });
        return false;
    });
    
    /*** Gift Competition ***/
    $(".giftnewsletterSignupBtn").click(function () {
        var emailForm = $("#giftnewsletterSignup");
        valid = true;
        emailadd = $("#giftnews-emailAddress").val();
        name = $("#giftnews-name").val();
        //validate email
        if(!checkEmail(emailadd)){
            $("#giftfeedbackMsg").html("Email is incorrect.")
                        .addClass("newsError");
            valid = false;
        }
        //validate name
        if(name == "" || name == " "){
            $("#giftfeedbackMsg").html("Name is required.")
                        .addClass("newsError");
            valid = false;
        }

        if(valid){
            $.ajax({
                url: "/Newsletters/AddSubscriber",
                type: "POST",
                data: $(emailForm).serialize(),
                success: function(data){
                    //set in CSS errorMsg to display:none
                    if(data.indexOf("Success") != -1){
                        $("#giftfeedbackMsg").removeClass();
                        $("#giftfeedbackMsg").html("<h3>Thank you for subscribing.</h3>"+
                                    "<p>Please check your email and click the confirm link. (Check your spam box if it does not appear in your inbox.)</p>")
                                    .addClass("newsSuccess")
                                    .show(1000);
                        $('#giftsubscriptionform').slideUp(500);
                        $('.add-signupsocial').slideDown(500);
                    }else{
                        $("#giftfeedbackMsg").removeClass();
                        $("#giftfeedbackMsg").html("<h3>Failed to add you.</h3><p>"+data+"</p>")
                                    .addClass("newsError")
                                    .show(1000);
                    }
                },
            });
        }else{
            $("#giftfeedbackMsg").show(1000);
        }
        return false;
    });

    //Hide social signup
    $('.add-signupsocial').hide();

    $('.compGift').click(function (e) {
        $('#gift-newsletter').modal({
            minHeight: 530,
            overlayClose: true,
            zIndex: 9999999,
            onOpen: function (dialog) {
                dialog.overlay.fadeIn('slow', function () {
                    dialog.container.slideDown('slow', function () {
                        dialog.data.fadeIn('slow');
                        var $a = $('.compGift');
                        var href = $a.attr('href');
                        var category = 'Competition Newsletter View'; // set this to whatever you want
                        var event = 'click'; // set this to whatever you want
                        var label = href; // set this to whatever you want
                        _gaq.push(['_trackEvent', category, event, href]);
                    });
                });
            },
            onClose: function (dialog) {
                dialog.data.fadeOut('slow', function () {
                    dialog.container.slideUp('slow', function () {
                        dialog.overlay.fadeOut('slow', function () {
                            $.modal.close(); // must call this!
                        });
                    });
                });
            }
        });
        return false;
    });
    /*** Gift Competition ***/
});

function checkEmail(email) {
    var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return pattern.test(email);
}

//intire page load - DOM, IMAGES AND SCRIPTS before executing.
$(window).load(function () {
    imgWidth = $("#articleImg").attr("width");
    var caption = $(".imgCollumn .caption");
    if (imgWidth < 300) {
        captionWidth = imgWidth - (parseInt(caption.css("padding-left")) + parseInt(caption.css("padding-right")));
        $(".imgCollumn").css("width", imgWidth + "px");
        caption.css("width", captionWidth + "px");
    }
    rotatorHeightEqual();
});

function rotatorHeightEqual() {
    mainImage = $(".main_image").css("height");
    thumbImage = $(".image_thumb").css("height");
    if (mainImage < thumbImage) {
        $(".main_image").css("height", thumbImage);
    }   
}

function shimmer() {
    $('.large_thumb_shine').css('left', '-120px').css('opacity', '0.8');
    $('.large_thumb_shine').animate({ left: '300px', 'opacity': '0' }, 700);
}

function arrayTestForValue(strValue, arrObject) {
    for (i = 0; i < arrObject.length; i++) {
        if (arrObject[i] == strValue) {
            return true;
        } else {
            return false;
        }
    }
}

function navRoundCorners() {
    $('#main_nav li a').corner('top');
    $('#subNavigation').corner('bottom');
    //$('.colHeading').corner('top');
    $('.tabHeading').corner('top');
    $('#breadcrumbs').corner('bottom');
}

function CompareTableFilter() {
    $(".filter").click(function () {
        var rel = $(this).attr("rel");

        if (rel != "all") {
            $(".CompareTable tr").each(function (index) {
                if ($(this).attr("class") == rel) {
                    //$("." + rel).css("visibility", "visible");
                    $("." + rel).css("display", "table-row");
                }
                else if ($(this).attr("class") != "headRow" && $(this).attr("class") != rel) {
                    //$(this).css("visibility", "collapse");
                    $(this).css("display", "none");
                    $(".filter").removeClass("tabSelected");
                }
            });
        } else {
            $(".CompareTable tr").each(function (index) {
                //$(this).css("visibility", "visible");
                $(this).css("display", "table-row");
                $(".filter").removeClass("tabSelected");
            });
        }
        $(this).addClass("tabSelected");
        return false;
    });
}

function ShowOnePartner()
{
    var partner = $(".ComparePartnerItem");
    var totalPartners = partner.length;
    var rand = Math.floor(Math.random()*totalPartners);

    partner.css("display", "none");
    partner.eq(rand).css("display", "block");
}

var rows2 = null;
var j = 0;
var randomnumber2 = 0;
var switchDelay2 = 5000;
var length2 = 0;

function Rotator() {
    if (rows2 == null) {
        rows2 = $("#tblPartner tr");
        length2 = rows2.length;
        randomnumber2 = Math.floor(Math.random() * (length2 / 2))
        j = randomnumber2 * 2;
    }

    if (j > length2 - 1) {
        j = 0;
    }

    rows2.each(function (index2) {
        if (index2 == j) {
            // $(this).fadeIn(2000);
            this.style.display = "block";
        }
        else {
            //$(this).fadeOut("slow");
            this.style.display = "none";
        }
    });
    j = j + 1;
    setTimeout("Rotator()", switchDelay2);
}

function performsearch() {
    var searchstring = document.getElementById('SearchText').value;
    var websearch = document.getElementById('searchradiobutton').checked;
    if (websearch == true) {
        window.location = "http://uk.search.yahoo.com/search?p=" + searchstring + "&ei=UTF-8&fr=cb-adfe&type=Finance&meta=all%3D1";
    }
    else {
        window.location = "http://uk.search.yahoo.com/search?p=" + searchstring + "&ei=UTF-8&fr=cb-adfe&type=Finance&meta=web*vs%3Dpolitics.co.uk%2C+myfinances.co.uk%2C+inthenews.co.uk%2C+aboutproperty.co.uk%2C+travelbite.co.uk";
    }
}

function addlogo() {
    document.getElementById('SearchText').style.background = "url('/images/horiz_pwrlogo_red.gif')";
}

function removelogo() {
    document.getElementById('SearchText').style.background = '#ffffff';
}

function fnTrapKeyDown(e) {
    document.onkeydown = fnTrapKeyDown;

    var intKeyPressed = document.all ? event.keyCode : e.which;

    if (intKeyPressed == 13) {
        document.getElementById('searchbutton').click();
        return false;
    }

}

function AJAXCompanyAZList(filter, element)
{
    $.ajax({
      url: '/companies-directory/company-search/',
      data : 'typeId=22&letterGroup='+filter ,
      type: 'POST',
      /*beforeSend: function( ) {
         $(element).slideUp();
      },*/
      success: function( data ) {
         $(element).slideUp(500, function(){
            $(element).html(data);
         });
         $(element).slideDown();
      }
    });
}

function CustomSearch1() {
    var keyword = document.getElementById("Keyword1").value;
    var url = "/search/?cx=partner-pub-9353229343941924:pp4td-fvydp&cof=FORID:10&ie=ISO-8859-1&q=" + keyword;
    window.location = url;
    return false;
}

function CustomSearch2() {
    var keyword = document.getElementById("Keyword2").value;
    var url = "/search/?cx=partner-pub-9353229343941924:pp4td-fvydp&cof=FORID:10&ie=ISO-8859-1&q=" + keyword;
    window.location = url;
    return false;
}
//Competition 
function CompOnOff(){
    var rand = Math.floor(Math.random() * 5);
    var segments = window.location.pathname.split("/");

    if(rand == 3 && segments.length != 2)
        $(".compGift").css("display", "inline");
}
//Image Preloader
function imgpreload(a, b) { if (b instanceof Function) { b = { all: b} } if (typeof a == "string") { a = [a] } var c = []; var t = a.length; var i = 0; for (i; i < t; i++) { var d = new Image(); d.onload = function () { c.push(this); if (b.each instanceof Function) { b.each.call(this) } if (c.length >= t && b.all instanceof Function) { b.all.call(c) } }; d.src = a[i] } } if (typeof jQuery != "undefined") { (function ($) { $.imgpreload = imgpreload; $.fn.imgpreload = function (b) { b = $.extend({}, $.fn.imgpreload.defaults, (b instanceof Function) ? { all: b} : b); this.each(function () { var a = this; imgpreload($(this).attr('src'), function () { if (b.each instanceof Function) { b.each.call(a) } }) }); var c = []; this.each(function () { c.push($(this).attr('src')) }); var d = this; imgpreload(c, function () { if (b.all instanceof Function) { b.all.call(d) } }); return this }; $.fn.imgpreload.defaults = { each: null, all: null} })(jQuery) }
