var gallerylength = 1;
var galleryLoaded = 0;

$(document).ready(function () {

    //$("#container").supersleight();



    $.preload(['subnav', 'single-line', 'double-line', 'double-line-on', 'single-line-on', 'subnav-last-line'], {
        base: '/style/images/',
        ext: '.png'
    });



    $(".subnav li:last-child, .signin li:last-child").addClass("last");
    Menu.Init();

    if ($("head").attr("rel")) {
        try {
            var img$ = GetImage($("head").attr("rel"));
            img$.addClass("on").attr('src', img$.attr("src").replace('_s1.png', '_s2.png'));
        } catch (e) {
        }
    }


    $("#mainnavigation li").hover(
		function () {
		    $("ul.subnav", this).show();
		},
		function () {
		    $("ul.subnav", this).hide();
		}
	);
    $(".subnav li").hover(
		function () {
		    $("ul.secondarynav", this).show();
		},
		function () {
		    $("ul.secondarynav", this).hide();
		}
	);

    $("li.signinlink").hover(
		function () {
		    $("ul", this).show();
		    $(this).addClass("loginhover");
		    $("#login .register").addClass("loginhover").addClass("registerhover");
		    //$("#search").hide();
		},
		function () {
		    $("ul", this).hide();
		    $(this).removeClass("loginhover");
		    $("#login .register").removeClass("loginhover").removeClass("registerhover");
		    //$("#search").show();
		}
	);


    $("#search input").watermark("Search News...", { className: 'red' });
    $("#search .mode a").click(function () {
        var c = "_s2.";
        var con = "_s1.";
        if ($(this).index() == 0) {
            $("#search input").watermark("Search News...", { className: 'red' });
        } else {
            $("#search input").watermark("Search Site...", { className: 'red' });
            c = "_s1.";
            con = "_s2.";
        }
        $("#search .mode img").each(function () {
            SetImage($(this), $(this).attr('src').replace(c, con));
        });
        return false;
    });

    // ********************** Ivan code **********************
    // Please check the how to replace "ctl00_QuickSearch1" with the .net function to 
    // pass the assigned ClientID for "rblSearchForOptions".
    if (($('#ctl00_QuickSearch1_rblSearchForOptions input[type=radio]:checked').val()) == "news") {
        $("#search input").watermark("Search News...", { className: 'red' });
    }
    else {
        $("#search input").watermark("Search Site...", { className: 'red' });
    }
    // ********************** End of Ivan code. **********************

    $("#searchfr input").watermark("Rechercher les nouvelles...", { className: 'red' });

    $("#searchfr .mode a").click(function () {
        var c = "_s2.";
        var con = "_s1.";
        if ($(this).index() == 0) {
            $("#searchfr input").watermark("Rechercher les nouvelles...", { className: 'red' });
        } else {
            $("#searchfr input").watermark("Recherche sur le site...", { className: 'red' });
            c = "_s1.";
            con = "_s2.";
        }
        $("#searchfr .mode img").each(function () {
            SetImage($(this), $(this).attr('src').replace(c, con));
        });
        return false;
    });
    // ********************** Ivan code **********************
    // Please check the how to replace "ctl00_QuickSearch1" with the .net function to
    // pass the assigned ClientID for "rblSearchForOptions".
    //if ($("#search .mode input[id$='Img1']").attr("src")  != null) alert($("#search .mode input[id$='Img1']") );
    if ($("#search .mode input[id$='Img1']").attr("src") != null) {
        if (($("#search .mode input[id$='Img1']").attr("src")).indexOf("search-news-fr") > 0) {
            if (($('#ctl00_QuickSearch1_rblSearchForOptions input[type=radio]:checked').val()) == "news") {
                $("#search input").watermark("Rechercher les nouvelles...", { className: 'red' });
            }
            else {
                $("#search input").watermark("Recherche sur le site...", { className: 'red' });
            }
        }
    }
    // ********************** End of Ivan code. **********************




    $("#categories > li > a").click(function () {
        if ($(this).hasClass("open")) {
            $("#categories > li > a").removeClass("open");
            $("#categories > li > ul").hide();
            if ($(this).attr("href") == "#") {
                return false;
            }
        } else {
            $("#categories > li > a").removeClass("open");
            $("#categories > li > ul").hide();
            $(this).addClass("open");
            $(this).next("ul").show();
            if ($(this).attr("href") == "#") {
                return false;
            }
        }
    });
    $('a.newsfeed').cluetip({
        width: 740,
        topOffset: -30,
        leftOffset: -845
    });

    $('a.related-news').cluetip({
        width: 400
    });


    $("a.group").fancybox({
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'speedIn': 600,
        'speedOut': 200,
        'overlayShow': true,
        'overlayColor': '#000000'
    });

    $(".watermark").each(function () {
        $(this).watermark($(this).attr("rel"), { className: 'gray' });
    });

    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Plan']"));
    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Create']"));
    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Share']"));
    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Listen']"));
    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Engage']"));
    CleanBreadCrums($("a.CMSBreadCrumbsLink[href='/Communication_Solutions/Analyze']"));


    if ($("#mycarousel").exists()) {
        var maxWidth = 90;
        var maxHeight = 68;
        gallerylength = $('a.itemmodal img').length;
        $('#mycarousel').before("<img id='LoadingGallery' src='/style/images/wait.gif'/>");
        var d = new Date().getTime();
        $('a.itemmodal img').each(function () {
            var img$ = $(this);
            img$.removeAttr("height");
            img$.removeAttr("width");
            var src = img$.attr("src") + "?" + d;
            var width = 0;
            var height = 0;
            var newWidth = 0;
            var newHeight = 0;
            $("<img/>").attr("src", src).load(function () {
                width = this.width;
                height = this.height;
                newWidth = width;
                newHeight = height;
                if (width > height && width > maxWidth) {
                    ratio = maxWidth / width;
                    newWidth = maxWidth;
                    newHeight = height * ratio;
                }
                else if (height > width && height > maxHeight) {
                    ratio = maxHeight / height;
                    newWidth = width * ratio;
                    newHeight = maxHeight;
                } else if (height == width) {
                    newWidth = maxHeight;
                    newHeight = maxHeight;
                }
                if (newWidth > maxWidth) {
                    newWidth = maxWidth;
                }
                if (newHeight > maxHeight) {
                    newHeight = maxHeight;
                }
                img$.attr("height", newHeight).attr("width", newWidth).attr("status", "resized");
            });

        });
        setTimeout("BuildGallery()", 100);
    } else {
        HideHandlers();
    }


    $("#handlers > li > a").click(function () {
        if ($(this).hasClass("open")) {
            $(this).removeClass("open");
            $(this).next("ul").hide();
        } else {
            $(this).addClass("open");
            $(this).next("ul").show();
        }
    });


    $("#expand a").click(function () {
        $("#handlers > li > a").addClass("open");
        $("#handlers > li > ul").show();
    });
    $("#collapse a").click(function () {
        $("#handlers > li > a").removeClass("open");
        $("#handlers > li > ul").hide();
    });

    $(".breadcrumb a").each(function () {
        var h = $(this).attr("href");
        if (h.charAt(h.length) != "/") {
            h = h + "/";
            h = h.replace("//", "/")
            $(this).attr("href", h.toLocaleLowerCase());
        }
    });



    $(".datatable tr:even").not("tr:first-child").addClass("highlight");


    $(".mw_release td:empty").append("&nbsp;");
    $('.mw_release table').wrap('<div class="scroll_table" />');

});
function CleanBreadCrums(l) {
    l.next().remove();
    l.remove();
}
jQuery.fn.exists = function () { return jQuery(this).length > 0; }

function BuildGallery() {
    galleryLoaded = $("a.itemmodal img[status='resized']").length;
    if (gallerylength == galleryLoaded) {
        $('#LoadingGallery').remove();
        $("a.itemmodal img").show();
        $("#mycarousel").jcarousel({
            scroll: 2,
            animation: 200,
            initCallback: function (o, i) {
                $("#handlers > li > ul").addClass("rightnewroom");
                HideHandlers();
                if (gallerylength < 3) {
                    $(".jcarousel-prev, .jcarousel-next").hide();
                }
            }
        });
    } else {
        setTimeout("BuildGallery()", 100);
    }
}
function HideHandlers() {
    $("#handlers > li > a:not(.open)").each(function () {
        $(this).next().hide();
    });
}


$.fn.imagesLoaded = function (callback) {
    var elems = this.filter('img'),
      len = elems.length;
    elems.bind('load', function () {
        if (--len <= 0) { callback.call(elems, this); }
    }).each(function () {
        // cached images don't fire load sometimes, so we reset src.
        if (this.complete || this.complete === undefined) {
            var src = this.src;
            // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
            // data uri bypasses webkit log warning (thx doug jones)
            this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
            this.src = src;
        }
    });
    return this;
};


function CheckItems() {
    $("ul.itemlist").each(function (index) {
        var ul = $(this);
        if (ul.find("li").size() > 3) {
            ul.next(".more").show();
            HideItems(ul);
        } else {
            ul.next(".more").hide();
        }
    });
}
function HideItems(o) {
    $(o).children("li").each(function (index) {
        if ((index + 1) > 3) {
            $(this).hide(0);
        }
    });
}
function ShowItems(o) {
    $(o).children("li").each(function (index) {
        $(this).show(0);
    });
}

function positionFooter() {


    var footerHeight = 150;
    var footerTop = ($(window).scrollTop() + $(window).height() - footerHeight) + "px";
    var footer = $("#footerbackground");

    //    console.log($(document.body).height());
    //    alert(footerTop);
    if (($(document.body).height()) > $(window).height()) {
        //        footer.css({
        //            top: footerTop
        //        })
        //      
        //        console.log("scroll");
        footer.removeClass("footerabsolute").addClass("footerstatic");
    } else {
        //        console.log("fit");
        footer.addClass("footerabsolute").removeClass("footerstatic");
        //      
        //    footer.addClass("footerabsolute");
        //        footer.removeClass("footerstatic").addClass("footerabsolute");
    }

}

function GetImage(alt) {
    var img$ = $(".hover img").filter(function (index) {
        return $(this).attr("alt") == alt;
    })
    return img$;
}
function SetImage(elt, src) {
    $(elt).attr('src', src);
}
Menu = {
    Init: function () {
        $('.hover img').preload({
            find: '_s1.png',
            replace: '_s2.png'
        });
        $('.hover img').hover(function () {
            Menu.Over(this);
        }, function () {
            Menu.Out(this);
        });
    },
    Over: function (elt) {
        if (!$(elt).hasClass('on')) {
            SetImage(elt, $(elt).attr('src').replace('_s1.', '_s2.'));
        }
    },
    Out: function (elt) {
        if (!$(elt).hasClass('on')) {
            SetImage(elt, $(elt).attr('src').replace('_s2.', '_s1.'));
        }
    }
}

/**
* Plugin: jquery.zRSSFeed
* 
* Version: 1.0.1
* (c) Copyright 2010, Zazar Ltd
* 
* Description: jQuery plugin for display of RSS feeds via Google Feed API
*              (Based on original plugin jGFeed by jQuery HowTo)
* 
* History:
* 1.0.1 - Corrected issue with multiple instances
*
**/

var MONTH_NAMES = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

(function ($) {

    var current = null;

    $.fn.rssfeed = function (url, options) {

        // Set pluign defaults
        var defaults = {
            limit: 10,
            header: false,
            titletag: 'h4',
            date: true,
            content: true,
            snippet: true,
            showerror: true,
            errormsg: '',
            key: null
        };
        var options = $.extend(defaults, options);

        // Functions
        return this.each(function (i, e) {
            var $e = $(e);

            // Add feed class to user div
            //if (!$e.hasClass('rssFeed')) $e.addClass('rssFeed');

            // Check for valid url
            if (url == null) return false;

            // Create Google Feed API address
            var api = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q=" + url;
            if (options.limit != null) api += "&num=" + options.limit;
            if (options.key != null) api += "&key=" + options.key;

            // Send request
            $.getJSON(api, function (data) {

                // Check for error
                if (data.responseStatus == 200) {

                    // Process the feeds
                    _callback(e, data.responseData.feed, options);
                } else {

                    // Handle error if required
                    if (options.showerror)
                        if (options.errormsg != '') {
                            var msg = options.errormsg;
                        } else {
                            var msg = data.responseDetails;
                        };
                    $(e).html('<li class="rssError"><p>' + msg + '</p></li>');
                };
            });
        });
    };

    // Callback function to create HTML result
    var _callback = function (e, feeds, options) {
        if (!feeds) {
            return false;
        }
        var html = '';

        // Add body
        //html += '<ul class="itemlist">';

        // Add feeds
        for (var i = 0; i < feeds.entries.length; i++) {

            // Get individual feed
            var entry = feeds.entries[i];

            // Format published date
            var entryDate = new Date(entry.publishedDate);
            //var pubDate = entryDate.toLocaleDateString() + ' ' + entryDate.toLocaleTimeString();


            //MONTH_NAMES
            // Add feed row
            html += '<li>';
            html += '<p class="title-date"><a href="' + entry.link + '" target="_blank" title="' + feeds.title + '">' + entry.title + '</a>';
            html += ' <span class="gray"> - ' + MONTH_NAMES[entryDate.getMonth()] + ". " + entryDate.getDate().toString() + '</span></p>'
            if (options.content) {
                if (options.snippet && entry.contentSnippet != '') {
                    var content = entry.contentSnippet;
                } else {
                    var content = entry.content;
                }
                html += '<p>' + content + '</p>'
            }
            html += '</li>';
        }
        //html += '</ul>';
        $(e).html(html);
        CheckItems();
    };
})(jQuery);


 
