/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options)
{
    if (typeof value != 'undefined')
    { // name and value given, set cookie
        options = options || {};
        if (value === null)
        {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString))
        {
            var date;
            if (typeof options.expires == 'number')
            {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else
            {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '; path=/';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else
    { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '')
        {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++)
            {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '='))
                {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

$(document).ready(function() {

    var inactive = "inactive";
    var active = "active";
    var focused = "focused";

    /*
    * This function places the label inside the textbox.
    * When the textbox is clicked, the text is removed.
    */
    $("label.label2value").each(function() {
        obj = document.getElementById($(this).attr("for"));
        if (($(obj).attr("type") == "text") || (obj.tagName.toLowerCase() == "textarea")) {
            $(obj).addClass(inactive);
            var text = $(this).text();
            $(this).css("display", "none");
            $(obj).val(text);
            $(obj).focus(function() {
                $(this).addClass(focused);
                $(this).removeClass(inactive);
                $(this).removeClass(active);
                if ($(this).val() == text) $(this).val("");
            });
            $(obj).blur(function() {
                $(this).removeClass(focused);
                if ($(this).val() == "") {
                    $(this).val(text);
                    $(this).addClass(inactive);
                } else {
                    $(this).addClass(active);
                };
            });
        };
    });

    // Robbrecommends, reset cookie
    var path = window.location.pathname;
    if (path.indexOf('/Robb-Recommends/') !== 0) {
        $.cookie('redirect_to_category', null);
        $.cookie('current_item', null);
    }

    // newsletter hide message
    $(".newsletter a").click(function() {
        $(".newsletter-window .newsletter-message").hide();
    });

    //Hide Media bar on pages
    CheckMediaBar();
});

//////////////////////////
// Chartis code //////////
//////////////////////////

//Chartis rotation
function chartisRotation(chartisCookie, numChartisAdds, rotate)
{
    var numRand = Math.floor(Math.random() * numChartisAdds);
    if (rotate == 1)
    {
        try
        {
            if ($.cookie(chartisCookie) != null)
            {
                if (numChartisAdds > 1)
                {
                    do
                    {
                        numRand = Math.floor(Math.random() * numChartisAdds);
                    } while ($.cookie(chartisCookie) == numRand);
                    $.cookie(chartisCookie, numRand);
                }
            }
            else
            {
                $.cookie(chartisCookie, numRand);
            }
            return numRand;
        }
        catch (error)
        {
            return numRand;
        }
    }
    else
    {
        try
        {
            if ($.cookie(chartisCookie) != null)
            {
                return $.cookie(chartisCookie);
            } else
            {
                return numRand;
            }
        } catch (error)
        {
            return numRand;
        }
    }
}
//Chartis Config
function chartisImagePath()
{
    return '../../Images/chartis/'; //Set the path for chartis adds
}
function getChartisHomeAdd(chartisType, rotate)
{
    //Set the number of chartis adds for home page
    var numChartisAdds = 1;
    var chartisHomeList = new Array(numChartisAdds);
    //List of chartis adds for home page
    for (var i = 0; i < numChartisAdds; i++)
        chartisHomeList[i] = new Array(4);

    chartisHomeList[0][0] = 'auto_210x400_exp.swf';
    chartisHomeList[0][1] = 'auto_210x400_collapsed.swf';
    chartisHomeList[0][2] = 'auto_210x400_backup.jpg';
    chartisHomeList[0][3] = 'ron.fiamma@chartisinsurance.com';

    if (chartisType == 'EXPANDED')
    {
        if (chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)] != null)
            return chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)][0];
    } else if (chartisType == 'BACKUP')
    {
        if (chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)] != null)
            return chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)][2];
    } else if (chartisType == 'EMAIL')
    {
        if (chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)] != null)
            return chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)][3];
    } else
    {
        if (chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)] != null)
            return chartisHomeList[chartisRotation('chartis_home_rotation', numChartisAdds, rotate)][1];
    }
}
function getChartisBackPagesAdd(chartisType, rotate)
{
    //Set the number of chartis adds for back pages
    var numChartisAdds = 6;
    var chartisBackList = new Array(numChartisAdds);
    //List of chartis adds for home page
    for (var i = 0; i < numChartisAdds; i++)
        chartisBackList[i] = new Array(5);

    chartisBackList[0][0] = 'home_300x200_exp.swf';
    chartisBackList[0][1] = 'home_300x200_collapsed.swf';
    chartisBackList[0][2] = '6';
    chartisBackList[0][3] = 'home_300x200_backup.jpg';
    chartisBackList[0][4] = 'ron.fiamma@chartisinsurance.com';
    chartisBackList[1][0] = 'watches_300x200_exp.swf';
    chartisBackList[1][1] = 'watches_300x200_collapsed.swf';
    chartisBackList[1][2] = '15';
    chartisBackList[1][3] = 'watches_300x200_backup.jpg';
    chartisBackList[1][4] = 'katja.zigerlig@chartisinsurance.com';
    chartisBackList[2][0] = 'wine_300x200_exp.swf';
    chartisBackList[2][1] = 'wine_300x200_collapsed.swf';
    chartisBackList[2][2] = '16';
    chartisBackList[2][3] = 'wine_300x200_backup.jpg';
    chartisBackList[2][4] = 'katja.zigerlig@chartisinsurance.com';
    chartisBackList[3][0] = 'jewelry_300x200_exp.swf';
    chartisBackList[3][1] = 'jewelry_300x200_collapsed.swf';
    chartisBackList[3][2] = '10';
    chartisBackList[3][3] = 'jewelry_300x200_backup.jpg';
    chartisBackList[3][4] = 'katja.zigerlig@chartisinsurance.com';
    chartisBackList[4][0] = 'home_300x200_exp.swf';
    chartisBackList[4][1] = 'home_300x200_collapsed.swf';
    chartisBackList[4][2] = '9';
    chartisBackList[4][3] = 'home_300x200_backup.jpg';
    chartisBackList[4][4] = 'ron.fiamma@chartisinsurance.com';
    chartisBackList[5][0] = 'auto_300x200_exp.swf';
    chartisBackList[5][1] = 'auto_300x200_collapsed.swf';
    chartisBackList[5][2] = '26';
    chartisBackList[5][3] = 'auto_300x200_backup.jpg';
    chartisBackList[5][4] = 'ron.fiamma@chartisinsurance.com';

    //Rotation
    var chartisCategoryID = $('.chartisCategoryID').html();
    var numRand;

    var existCHartisCategoryID = false;
    for (var i = 0; i < numChartisAdds; i++)
    {
        if (chartisBackList[i][2] == chartisCategoryID)
        {
            existCHartisCategoryID = true;
            numRand = i;
            i = numChartisAdds;
        }
    }

    if (!existCHartisCategoryID)
    {
        if (chartisType == 'EXPANDED')
        {
            if (chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)] != null)
                return chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)][0];
        } else if (chartisType == 'BACKUP')
        {
            if (chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)] != null)
                return chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)][3];
        } if (chartisType == 'EMAIL')
        {
            if (chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)] != null)
                return chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)][4];
        } else
        {
            if (chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)] != null)
                return chartisBackList[chartisRotation('chartis_back_rotation', numChartisAdds, rotate)][1];
        }
    } else
    {
        if (chartisType == 'EXPANDED')
        {
            return chartisBackList[numRand][0];
        } else if (chartisType == 'BACKUP')
        {
            return chartisBackList[numRand][3];
        } else if (chartisType == 'EMAIL')
        {
            return chartisBackList[numRand][4];
        } else
        {
            return chartisBackList[numRand][1];
        }
    }
}
function chartisAddType(chartisType)
{
    if (chartisType == 'EXPANDED')
    {
        return 'flash1';
    } else
    {
        return 'flash2';
    }
}
//Create chartis add
function chartisCreateAdd(chartisType, chartisAdd, rotate)
{
    var addName = '';
    var addNameBackup = '';
    var addEmail = '';

    if (chartisAdd == 'HOME')
    {
        addName = getChartisHomeAdd(chartisType, rotate);
        addNameBackup = getChartisHomeAdd('BACKUP', rotate);
        addEmail = getChartisHomeAdd('EMAIL', rotate);
    } else
    {
        addName = getChartisBackPagesAdd(chartisType, rotate);
        addNameBackup = getChartisBackPagesAdd('BACKUP', rotate);
        addEmail = getChartisBackPagesAdd('EMAIL', rotate);
    }

    if (addName != null && addName != "")
        return '<object id="' + chartisAddType(chartisType) + '" data="' + (chartisImagePath() + addName) + '" type="application/x-shockwave-flash" width="100%" height="100%" ><param name="wmode" value="transparent" /><param name="movie" value="' + (chartisImagePath() + addName) + '" /><param name="scale" value="exactfit" /><param name="allowScriptAccess" value="always" /><a href="mailto:' + addEmail + '?cc=chartisinquiry@robbreport.com&subject=Insurance Inquiry from a Robb Report VIP"><img src="' + (chartisImagePath() + addNameBackup) + '" alt="" /></a><script type="text/javascript">chartisNoFlashHide();</script></object>'
    else
        return '';
}

//Get the chartis class for back pages
function getChartisClass()
{
    //Global Master and Virtual Marina Master
    var addNormal = '.chartis-big-global';
    //Market Place Master
    if ($('.chartis-big-mp-colapsed').offset() != null)
    {
        addNormal = '.chartis-big-mp';
    }
    //RRR Master
    if ($('.chartis-big-rrr-colapsed').offset() != null)
    {
        addNormal = '.chartis-big-rrr';
    }

    return addNormal;
}

//Get Home Page Cookie state
function chartisHomeCookie()
{
    //generate chartis add colapsed on home page
    if ($('#flash2').offset() == null)
    {
        if ($('.chartis-big-home-colapsed').offset() != null)
        {
            $('.chartis-big-home-colapsed').append(chartisCreateAdd('COLAPSED', 'HOME', 1));
        }
    }
    //verify cookie
    try
    {
        if ($.cookie('chartis_home') == "True")
        {
            return true;
        }
        else
        {
            return false;
        }
    } catch (Error)
    {
        return true;
    }
}
//Get Back Pages Cookie state
function chartisBackPagesCookie()
{
    //generate chartis add colapsed on back pages
    if ($('#flash2').offset() == null)
    {
        var addNormal = getChartisClass();
        var addColapsed = '-colapsed';
        $(addNormal + addColapsed).append(chartisCreateAdd('COLAPSED', 'BACK', 1));
    }
    // get cookie name
    var chartisCategoryID = $('.chartisCategoryID').html();
    var cookieName = 'chartis_back_pages_' + chartisCategoryID;
    //verify cookie
    try
    {
        if ($.cookie(cookieName) == "True")
        {
            return true;
        }
        else
        {
            return false;
        }
    } catch (error)
    {
        return true;
    }
}

//Chartis cookie verification
function chartiesCookie()
{
    //Home Page   
    if (chartisHomeCookie())
    {
        $('#fifth-column .chartis-big-home').remove();
        $('#fifth-column .chartis-home-wrapper').remove();
    }
    else
    {
        if ($('#flash1').offset() == null)
        {
            //Generate animated add
            $('.chartis-big-home').append(chartisCreateAdd('EXPANDED', 'HOME', 0));
        }
    }
    //Back Pages
    if (chartisBackPagesCookie())
    {
        var addNormal = getChartisClass();
        var addColapsed = '-colapsed';

        if ($(addNormal + addColapsed).offset != null)
        {
            $(addNormal).remove();
            $('.chartis-wrapper').remove();
            $('.chartis-wrapper-vm').remove();
            $('.chartis-wrapper-mp').remove();
            $('.chartis-wrapper-rrr').remove();
        }
    }
    else
    {
        if ($('#flash1').offset() == null)
        {
            var addNormal = getChartisClass();
            //Generate animated add
            $(addNormal).append(chartisCreateAdd('EXPANDED', 'BACK', 0));
        }
    }
    //Change the position of the chartis if the corner peel is presente on the page
    if ($('.CornerPeel').offset() != null)
    {
        $('.chartis-wrapper').css('top', 455);
    }

};
// Begin Chartis animation on scroll
$(window).scroll(function()
{
    //Home page
    if (!chartisHomeCookie())
    {
        if ($('.chartis-home-page').offset() != null)
        {
            if ($(window).scrollTop() + $(window).height() >= $('.chartis-wrapper-2').offset().top + $('#fifth-column').height())
            {
                if ($('#flash1').offset() == null)
                {
                    //Generate animated add
                    chartisReplayAnimation();
                    // set the cookie
                    $.cookie('chartis_home', 'True', { expires: 1 });
                }
            }
        }
    }
    //Back pages
    if (!chartisBackPagesCookie())
    {
        if ($('.chartis').offset() != null)
        {
            if ($(window).scrollTop() + $(window).height() >= $('.chartis-wrapper-2').offset().top + $('.chartis-wrapper-2').height() + 200)
            {
                var addNormal = getChartisClass();
                var addColapsed = '-colapsed';
                if ($('#flash1').offset() == null)
                {
                    //Generate animated add
                    chartisReplayAnimation();
                    // set the cookie
                    var chartisCategoryID = $('.chartisCategoryID').html();
                    var cookieName = 'chartis_back_pages_' + chartisCategoryID;
                    $.cookie(cookieName, 'True', { expires: 1 });                    
                }
            }
        }
    }
});
function chartisNoFlashHide()
{
    var hasFlash = false;
    try
    {
        var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
        if (fo) hasFlash = true;
    } catch (e)
    {
        if (navigator.mimeTypes["application/x-shockwave-flash"] != undefined) hasFlash = true;
    }
    if (!hasFlash)
    {
        chartisFlashAnimationCompleted();
    }
}

//Chartis animation complete
function chartisFlashAnimationCompleted()
{
    //Home Page
    if ($('#fifth-column .chartis-big-home').offset() != null)
    {
        $('#fifth-column .chartis-big-home').fadeOut();
        $('#fifth-column .chartis-big-home').remove();
        //$.cookie('chartis_home', 'True', { expires: 1 });

        // if this is after a replay
        if ($('.chartisReplayWrapper').offset() != null)
            $('.chartisReplayWrapper').remove();
    }

    //Back Pages

    if ($('.chartis-wrapper').offset() != null)
    {
        $('.chartis-wrapper').fadeOut(function() { $('.chartis-wrapper').remove(); });
    }

    if ($('.chartis-wrapper-vm').offset() != null)
    {
        $('.chartis-wrapper-vm').fadeOut(function() { $('.chartis-wrapper-vm').remove(); });
    }

    if ($('.chartis-wrapper-rrr').offset() != null)
    {
        $('.chartis-wrapper-rrr').fadeOut(function() { $('.chartis-wrapper-rrr').remove(); });
    }

    if ($('.chartis-wrapper-mp').offset() != null)
    {
        $('.chartis-wrapper-mp').fadeOut(function() { $('.chartis-wrapper-mp').remove(); });
    }

    if ($(getChartisClass() + '-expanded').offset() != null)
    {
        var addNormal = getChartisClass();
        var addColapsed = '-expanded';

        // if this is after a replay
        if ($('.chartisReplayWrapper').offset() != null)
            $('.chartisReplayWrapper').remove();

        // hide the expanded div
        if ($(addNormal + addColapsed).offset() != null)
        {
            $(addNormal + addColapsed).fadeOut();
            //$(addNormal + addColapsed).remove();
            //var chartisCategoryID = $('.chartisCategoryID').html();
            //var cookieName = 'chartis_back_pages_' + chartisCategoryID;
            //$.cookie(cookieName, 'True', { expires: 1 });
        }
    }
};
function chartisReplayAnimation()
{
    //Home page
    if ($('#fifth-column .chartis-big-home-colapsed').offset() != null)
    {
        if ($('#flash1').offset() == null)
        {
            var section = 'chartis-big-home';
            var hide = $('.chartis-home-page').html();
            //Generate animated add
            $('#fifth-column .chartis-home-page-expanded').load('/chartisReplay.html', function() { $('.chartisReplayWrapper').append('<div class="' + section + '">' + chartisCreateAdd('EXPANDED', 'HOME', 0) + '</div>'); });
        }
    }
    //Back Pages
    if ($('.chartis').offset() != null)
    {
        if ($('#flash1').offset() == null)
        {
            var section = getChartisClass() + '-expanded';
            //Generate animated add
            $(section).show();
            $(section).load('/chartisReplay.html', function() { $('.chartisReplayWrapper').append('<div style="width:430px; height:340px;">' + chartisCreateAdd('EXPANDED', 'BACK', 0) + '</div>'); });
        }
    }
}
// End Chartis run animation on scroll

///////////////////
//HIDE MEDIA BAR //
///////////////////
function CheckMediaBar() {
    if ($('.ArticleList .articles-top').offset() != null) {
        var divHtml = $('.ArticleList .articles-top').html();
        if (divHtml == null || divHtml.trim() == '') {
            $('.ArticleList .articles-top').remove();
            $('#articleListSeparator').remove();
            $('.articles-bottom').attr('style', 'margin-top:0;');
            $('.articles-bottom div span').attr('style', 'display: inline;');
            $('.ArticleList .PagingPanel').attr('style', 'margin-top: 55px;');
        }
    }
}

var infiniteLoop;
var infiniteLoopPause = false;

Sys.Application.add_load(function()
{
    // set handlers for rotating sponsored features on category pages
    $('.rotating-element').mouseover(function(e)
    {
        infiniteLoopPause = true;
    });
    $('.rotating-element').mouseout(function(e)
    {
        infiniteLoopPause = false;
    });

    // adjust layout for smaller monitors
    if ($(window).width() <= 1280)
        $('.inner-wrapper').css('width', '1263px');
});

function RotateElementsDescending(interval, duration)
{
    var elementsCount = $('.rotating-element').length;

    if (elementsCount <= 0)
        return;

    var currentElement = elementsCount - 1;

    interval += duration;

    infiniteLoop = setInterval(function()
    {
        if (infiniteLoopPause == false)
        {
            $('.rotating-element').eq(currentElement).fadeOut(duration, function()
            {
                if (currentElement <= 0)
                    currentElement = elementsCount - 1;
                else
                    currentElement--;

                $('.rotating-element').eq(currentElement).fadeIn(duration);
            });
        }

    }, interval);
}


