/**
 * Classe McString
 */

function McString(value) {
    this.value = value;

    if(typeof McString.initialized == "undefined") {
        McString.prototype.toUrl = function() {
            var chaine = this.value;
            
            chaine = chaine.toLowerCase();
            chaine = chaine.replace(/[àâä]/gi,"a");
            chaine = chaine.replace(/[éèêë]/gi,"e");
            chaine = chaine.replace(/[îï]/gi,"i");
            chaine = chaine.replace(/[ôö]/gi,"o");
            chaine = chaine.replace(/[ùûü]/gi,"u");
            chaine = chaine.replace(/(ùûü)/gi,"u");
            chaine = chaine.replace(/(ç)/gi, '-');
            chaine = chaine.replace(/( +)/g, '-');
            chaine = chaine.replace(/('+)/g, '-');
            //chaine = chaine.replace(/(,+)/g, '-');
            //chaine = chaine.replace(/(;+)/g, '-');
            //chaine = chaine.replace(/(:+)/g, '-');
            //chaine = chaine.replace(/(!+)/g, '-');
            //chaine = chaine.replace(/(?+)/g, '-');
            chaine = chaine.replace(/("+)/g, '-');
            chaine = chaine.replace(/(_+)/g, '-');
            chaine = chaine.replace(/(-+)/g, '-');
            chaine = chaine.replace(/^-/g, '');
            chaine = chaine.replace(/-$/g, '');
            return chaine;
        }

        McString.initialized = true;
    }
}

/*
 * onload
 */
$(document).ready(function() {
    $('.catalog h2,.catalog h3').before('<div style="clear:both;" />');

    // slideshows
    function onCycleAfter(curr, next, opts, fwd) {
        var index = opts.currSlide;
        $('#prev')[index == 0 ? 'hide' : 'show']();
        $('#next')[index == opts.slideCount - 1 ? 'hide' : 'show']();
        //get the height of the current slide
        var $ht = $(this).height();
        //set the container's height to that of the current slide
        $(this).parent().css("height", $ht);
    }
    $('.slideshow').cycle({
        fx: 'scrollLeft,scrollDown,fade,scrollRight,scrollUp,fade,growX,growY,fade,turnDown,turnLeft,turnRight',
        randomizeEffects: false,
        speed:  1500,
        pause: 1,
        random:  1,
        timeout: 5000
        //after: onCycleAfter
    });

    //$( "#tabs" ).tabs();
    $( "#accordion" ).accordion({collapsible: true,autoHeight: false});
    $( "#sortable" ).sortable();

    /**
     * Forumulaires ajax
     */
    $('#myform').ajaxForm({
        target:'#formResponse',
        beforeSubmit:formRequest,
        success:formResponse,
        dataType:'json'
        //clearForm:true
    });

    /**
     * L'identifiant d'URL est transformé en minuscules
     */
    $("input#kid").change(function () {
        var value = $(this).attr("value");
        var mcString = new McString(value);
        $(this).attr("value",mcString.toUrl());
    });


});

/*
 * Forms
 */
function formRequest(formData, jqForm, options) {
    $("#formLoading").slideDown("slow");
    return true;
}

function formResponse(data, statusText, xhr, $form)  {
    //data = jQuery.parseJSON(data);
    $('#myform ul.errors').remove();
    var $dialog = $('<div></div>').dialog({
        title: 'Saisie du formulaire',
        autoOpen: false,
        width: 400,
        modal: true,
        position: 'center',
        buttons: {"Ok": function() {$(this).dialog("close");}}
    });
               
    if(data.success == true) {
        $form.clearForm();
        $dialog.html('Votre commentaire va être publié dans les meilleurs délais (La publication devient généralement effective avant 48h).').dialog('open');
    } else {
        
        $dialog.html('Merci de contrôler les éléments renseignés dans le formulaire.').dialog('open');
        //$("#myform").slideDown("slow");
        //alert(data.debug);
        var messages = data.message;
        //formElement.append(getErrorHtml(errors , element));
        for(var element in messages) {
            var errors = messages[element];
            /*for(var errorType in errors) {
                alert(element + ' ' + errorType + ' ' + errors[errorType]);
            }*/
            var formElement = $('#myform label[for=' + element + ']');
            formElement.after(getErrorHtml(errors , element));
        }

    }
    $("#formLoading").slideUp("slow");
    return false;
}

function getErrorHtml(formErrors , id)
{
    var o = '<ul id="errors-'+id+'" class="errors">';
    for(errorKey in formErrors)
    {
        o += '<li>' + formErrors[errorKey] + '</li>';
    }
    o += '</ul>';
    return o;
}

/**
 * Addthis
 */

function addBookmark(title, url) {
    if (window.sidebar) { // firefox
        window.sidebar.addPanel(title, url,"");
    } else if( document.all ) { //MSIE
        window.external.AddFavorite( url, title);
    } else {
        alert("Désolé, votre navigateur ne supporte pas cette fonctionnalité");
    }
}

function goToUrl(url) {
    setTimeout('document.location = "' + url + '"', 100);
}

function openUrl(url) {
    setTimeout(window.open(url, "social"), 100);
}

function addthis(service) {
    var title = $("title").html();
    var url = document.URL;

    /*var pathName = window.location.pathname;
    pathName = pathName.split("/");
    pageName = pathName[pathName.length - 1];
    pageName = pageName.substr(0, pageName.lastIndexOf("."));
    pageName = pageName.replace(new RegExp("(%20|_|-)", "g"), "");*/

    var addthis_url;
    switch(service) {
        case 'facebook':
            addthis_url = 'http://www.facebook.com/share.php?u=' + url + '&title=' + encodeURIComponent(title) + '';
            openUrl(addthis_url);
            break;
        case 'twitter':
            addthis_url = 'http://twitter.com/home?status=' + encodeURIComponent(title) + '+' + url + '';
            openUrl(addthis_url);
            break;
        case 'favorite':
            addBookmark(title,url);
            break;
        case 'email':
            addthis_url = 'mailto:?subject=' + encodeURIComponent(title) + '&body=' + url;
            goToUrl(addthis_url);
            break;
    }
    _gaq.push(['_trackEvent', 'Addthis', service, url]);
    return false;
}





