/// <reference path="jquery/jquery-1.4.1-vsdoc.js" />
/// <reference path="jhash-1.0.0.js" />

$(document).ready(function ()
{
	var Ajax = true;
	
    // Gestion de l'historique "ie, moz, webkit"
    function hashChanged()
    {
        var url = jHash.val('url');
		if(typeof(url)=='undefined') url = "";
		url = url.replace(document.location.protocol + "//" + document.location.host, '');
		url = document.location.protocol + "//" + document.location.host + url;
		url = url.replace(" ", "%20");
		piwikTracker.setCustomUrl(url);
        $('#Ajax').load(url + " #UPPage", { Ajax: 1 });
    };
    jHash.change(hashChanged);
	if (jHash.hash())
	{
		hashChanged();
	}
	//piwikTracker.setHeartBeatTimer('5', '10');

	function nav(url)
	{
		url = url.replace(/^.*#/, '');
		url = url.replace(document.location.protocol + "//" + document.location.host, '');
		jHash.set({url : url, ts : new Date().getTime()});
	};
	
    $('#HTMLTitre').livequery(function ()
    {
        document.title = $(this).text();
		piwikTracker.trackPageView($(this).text());	
    });
	
	$('a.piwik_download').livequery('click', function (event)
	{
		piwikTracker.trackLink( $(this).attr("href"), 'download' );
	});
	$('a.piwik_link, .Energie2007Lien a').livequery('click', function (event)
	{
		piwikTracker.trackLink( $(this).attr("href"), 'link' );
	});

	// slider
	$(".flexslider").livequery(function ()
    {
		$(this).flexslider({
			animation: "fade",              //String: Select your animation type, "fade" or "slide"
			slideDirection: "horizontal",   //String: Select the sliding direction, "horizontal" or "vertical"
			slideshow: true,                //Boolean: Animate slider automatically
			slideshowSpeed: 3000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
			animationDuration: 500,         //Integer: Set the speed of animations, in milliseconds
			directionNav: true,             //Boolean: Create navigation for previous/next navigation? (true/false)
			controlNav: true,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
			keyboardNav: true,              //Boolean: Allow slider navigating via keyboard left/right keys
			mousewheel: true,              //Boolean: Allow slider navigating via mousewheel
			prevText: "Précédent",           //String: Set the text for the "previous" directionNav item
			nextText: "Suivant",               //String: Set the text for the "next" directionNav item
			pausePlay: false,               //Boolean: Create pause/play dynamic element
			pauseText: 'Pause',             //String: Set the text for the "pause" pausePlay item
			playText: 'Démarrer',               //String: Set the text for the "play" pausePlay item
			randomize: false,               //Boolean: Randomize slide order
			slideToStart: 0,                //Integer: The slide that the slider should start on. Array notation (0 = first slide)
			animationLoop: true,            //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
			pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
			pauseOnHover: false,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
			controlsContainer: "",          //Selector: Declare which container the navigation elements should be appended too. Default container is the flexSlider element. Example use would be ".flexslider-container", "#container", etc. If the given element is not found, the default action will be taken.
			manualControls: "",             //Selector: Declare custom control navigation. Example would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
			start: function(){},            //Callback: function(slider) - Fires when the slider loads the first slide
			before: function(){},           //Callback: function(slider) - Fires asynchronously with each slider animation
			after: function(){},            //Callback: function(slider) - Fires after each slider animation completes
			end: function(){}               //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
		});
	});
	

	
    // Autocomplete
    $("input[type='text'].autocomplete").livequery(function ()
    {
        $(this).autocomplete($(this).parent('form').attr("action"), { max: 10, scrollHeight: 300, extraParams: { i: $(this).attr("name")} });
    });
	    // Autocomplete
    $("input[type='text'].autocomplete.autoredirect").livequery(function ()
    {
        $(this).result(function (event, data, formatted) {
			//$(this).parent('form').submit();
			nav($(this).parent('form').attr("action") + "/" + $(this).attr("name") + "/" + $(this).attr("value"));
		});
    }, function ()
    {
        $(this).unbind("result")
    });
	$("input[type='text'].autocomplete.autosubmit").livequery(function ()
    {
        $(this).result(function (event, data, formatted) {
			$(this).parent('form').submit();
		});
    }, function ()
    {
        $(this).unbind("result")
    });
	
	// AJAX
	if (Ajax) {
		// Ajax Liens et Menu
		$('a.Ajax, li.Menu ul li a').livequery('click', function (event)
		{
			var url = $(this).attr('href');
			nav(url);
			return false;
		});
		// Ajax des formulaires
		$('form.Ajax:has(input[name="Target"])').livequery(function ()
		{
			$(this).ajaxForm(
			{
				data: { Ajax: 1 },
				success: function (responseText, statusText, xhr, form)
				{
					target = $(form).children('input[name="Target"]').val();
					$(target).html($(responseText).find(target).html());
				}
			});
		});
	};
    // Alternance des lignes <table><tbody><tr>
    $('table.alterne tbody tr:even').livequery(function () { $(this).addClass("even"); });
    $('table.alterne tbody tr:odd').livequery(function () { $(this).addClass("odd"); });

    // Animation du menu principal
    $(".Menu").each(function ()
    {
        var H = $(this).children('ul').hide().height();
        $(this).mouseover(function ()
        {
            $(this).children('ul').height(H);
            $(this).children('ul').stop().animate(
            { height: 'show' },
            { queue: false,
                duration: 250,
                easing: 'swing'
            })
        });
        $(this).mouseout(function ()
        {
            $(this).children('ul').stop().animate(
            { height: 'hide' },
            { queue: false,
                duration: 250,
                easing: 'swing'
            });
        });
    });


	// Skin iframe Piwik
	$('iframe.piwik').livequery('load',function ()
	{
		$(this).contents().find("body").css("font-family", "Arial,Helvetica,sans-serif");
		$(this).contents().find("body").css("font-size", 12);
	});

    // Skin des formulaires
    $(':checkbox').livequery(function ()
    {
        $(this).hide();
        var ckb = $(this);
        var ckbskin = $("<span class='skincheckbox'></span>").insertBefore($(this));
        var ckblabel = $("label[for=" + ckb.attr('id') + "]");
        $(ckb).change(function ()
        {
            if ($(this).is(':checked'))
            {
                $(ckbskin).addClass("checked");
            } else
            {
                $(ckbskin).removeClass("checked");
            };
        });
        $(ckbskin).click(function ()
        {
            $(ckb).attr('checked', !$(ckb).attr('checked'));
            ckb.change();
        }).mousedown(function ()
        {
            $(ckbskin).addClass("highlight");
        }).mouseup(function ()
        {
            $(ckbskin).removeClass("highlight");
        });

        ckb.hover(function ()
        {
            $(ckbskin).addClass("highlight");
        }, function ()
        {
            $(ckbskin).removeClass("highlight");
        });

        ckblabel.hover(function ()
        {
            $(ckbskin).addClass("highlight");
        }, function ()
        {
            $(ckbskin).removeClass("highlight");
        });
        ckb.change();
    });

    $(':radio').livequery(function ()
    {
        $(this).hide();
        var ckb = $(this);
        var ckbskin = $("<span class='skinradio'></span>").insertBefore($(this));
        var ckblabel = $("label[for=" + ckb.attr('id') + "]");
        $(ckb).change(function ()
        {
            var r = $(':radio[name=' + $(this).attr('name') + ']').prev();
            $(':radio[name=' + $(this).attr('name') + ']').prev().removeClass("checked");
            if ($(this).is(':checked'))
            {
                $(ckbskin).addClass("checked");
            };
        });
        $(ckbskin).click(function ()
        {
            $(ckb).attr('checked', true);
            ckb.change();
        }).mousedown(function ()
        {
            $(ckbskin).addClass("highlight");
        }).mouseup(function ()
        {
            $(ckbskin).removeClass("highlight");
        });

        ckb.hover(function ()
        {
            $(ckbskin).addClass("highlight");
        }, function ()
        {
            $(ckbskin).removeClass("highlight");
        });

        ckblabel.hover(function ()
        {
            $(ckbskin).addClass("highlight");
        }, function ()
        {
            $(ckbskin).removeClass("highlight");
        });
        ckb.change();
    });

    // Redimensionne les titre h1
    $("h1").livequery(function ()
    {
        while ($(this).width() >= 490 && parseInt($(this).css('font-size')) > 4)
        {
            $(this).css("font-size", (parseInt($(this).css('font-size')) - 1) + "px");
        };
    });







    // Anim Top Page
    $("#HautDePage").live('click', function (event)
    {
        event.preventDefault();
        $('html, body').animate({ scrollTop: 0 }, 'normal');
    });

    customClose = function ()
    {
        return '<div class="customClose" style="float:right" onclick="Shadowbox.close()"> FERMER</div>';
    };

    // Shadowbox lien Energie 2007
    $("#Energie2007Detail a").live('click', function (event)
    {
        event.preventDefault();
        Shadowbox.open({
            content: $(this).attr("href"),
            player: "iframe",
            title: " Energie 2007" + customClose(),
            width: 1200,
            options: {
                displayNav: false
            }
        });
    });

    // Tooltip
    $('.tooltiptitle').livequery(function ()
    {
        $(this).tooltip({
            track: true,
            delay: 0,
            showURL: false,
            showBody: " - ",
            extraClass: "tooltip",
            fade: 250,
            left: -125,
            top: 25
        });
    });


    // Shadowbox les cartes du département, et images de dossiers trad
    $("a:has(img.Departement)").live('click', function (event)
    {
        event.preventDefault();
        var HandlePlayer = function (e)
        {
//            var img = $('#sb-player')[0];
//            $("#sb-title-inner").html((e.layerX - img.offsetLeft) + ' ' + (e.layerY - img.offsetTop));
//            $.get(img.src, {
//                X: e.layerX - img.offsetLeft,
//                Y: e.layerY - img.offsetTop
//            }, function (data, textStatus, jqXHR)
//            {
//                alert(data);
//            });
        };
        Shadowbox.open({
            content: '',
            player: "img",
            content: $(this).attr('href'),
            title: " " + $(this).children('img').attr('alt') + customClose(),
            options: {
                autoDimensions: true,
                handleOversize: 'drag',
                displayNav: false,
                onFinish: function ()
                {
                    $('#sb-body-inner').bind("click", HandlePlayer);
                },
                onClose: function ()
                {
                    $('#sb-body-inner').unbind("click", HandlePlayer)
                }
            }
        });
    });
	


    // Shadowbox les autres liens .box
    $("a.box").live('click', function (event)
    {
        event.preventDefault();
        Shadowbox.open({
            content: $(this).attr("href"),
            player: "iframe",
            title: " " + $(this).text() + customClose(),
            options: {
                displayNav: false
            }
        });
    });

    // Shadowbox PDF       exclus
    // $("a.pdfbox, .Fichier.PDF a").live('click', function (event)
    // {
        // event.preventDefault();
        // Shadowbox.open({
            // content: '<object data="' + $(this).attr("href") + '" type="application/pdf" width="100%" height="100%">' +
                        // '<embed src="' + $(this).attr("href") + '" type="application/pdf" width="100%" height="100%"/>' +
                     // '</object>',
            // player: "html",
            // title: " " + $(this).text() + customClose(),
            // width: screen.width,
            // height: screen.height,
            // options: {
                // handleOversize: 'none',
                // handleUnsupported: "link",
                // displayNav: false
            // }
        // });
    // });


    // Shadowbox les images .imgbox
    $("a.imgbox").live('click', function (event)
    {
        event.preventDefault();
        Shadowbox.open({
            content: '',
            player: "img",
            content: $(this).attr('href'),
            title: " " + $(this).children('img').attr('alt') + customClose(),
            options: {
                autoDimensions: true,
                handleOversize: 'drag',
                displayNav: false
            }
        });
    });

    // Anime l'ouverture et fermeture des permanents
    $('.Perma1, .Perma2, #Energie2007, h2').live('click', function ()
    {
        var premier = $(this).next();
        if (premier.is(':visible'))
        {
            premier.slideUp("slow");
        } else
        {
            premier.slideDown("slow");
        };
    });


    // @
    $("span.Contact").livequery(function ()
    {
        $(this).append("<a href='mailto:" + $(this).attr("title") + "@sied70.fr'>" + $(this).attr("title") + "@sied70.fr</a>");
    });


    // Charge le flus RSS à partir du site Energie 2007
    if (document.getElementById("Energie2007Detail"))
    {
        var feed = new google.feeds.Feed("http://www.energie2007.fr/rss/");
        feed.includeHistoricalEntries();
        feed.setNumEntries(10);
        feed.load(function (result)
        {
            if (!result.error)
            {
                $("#Energie2007Detail").empty();
                for (var i = 0; i < result.feed.entries.length; i++)
                {
                    var entry = result.feed.entries[i];

                    $("#Energie2007Detail").append("<span class='Energie2007Date'>" + new Date(entry.publishedDate).dateFormat("l j F", "fr") + "</span><span class='Energie2007Lien'><a href='" + entry.link + "'>" + entry.title + "</a></span>");
                };
                $("#Energie2007Detail").slideDown("normal");
            };
        });
    };

    $("#map-canvas").livequery(function ()
    {
        var mapDiv = document.getElementById('map-canvas');
        var map = new google.maps.Map(mapDiv, {
            center: new google.maps.LatLng(47.850501865113991, 6.2275646011720891),
            zoom: 9,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        var json = WebService.Adherents(function (response)
        {
            Adherents(response, map);
        });
    });
});



