if (window['console'] == undefined){
  console = { log:function() {} }
}

function _alert(text) {
    alert(text)
}
function slugify(text) {
        text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
        text = text.replace(/-/gi, "_");
        text = text.replace(/\s/gi, "-");
        return text;
}

function favorite(name, url, category) {
    if (category == undefined){
        category = "General"
    }
    $.post("/favorite/", "name="+encodeURIComponent(name)+"&url="+escape(url)+"&category="+category, function() {
        _alert("Page ajoutée à vos favoris")
    })
}

function add_image_favorite(name, id, gallery_id) {
    category = "image"

    $.post("/favorite/", "name="+encodeURIComponent(name)+"&url=/gallerypicture/"+id+"&category=image", function() {
        _alert("Page ajoutée à vos favoris")
    })
}

String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

/***********************************************
 * Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
 * This notice MUST stay intact for legal use
 * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
 ***********************************************/

function bookmarksite(title,url){
    if (window.sidebar) // firefox
        window.sidebar.addPanel(title, url, "");
    else if(window.opera && window.print){ // opera
        var elem = document.createElement('a');
        elem.setAttribute('href',url);
        elem.setAttribute('title',title);
        elem.setAttribute('rel','sidebar');
        elem.click();
    } else  if (window.chrome) {
      alert('Appuyez sur Ctrl + D pour mettre en favori (Command + D sur Mac) après avoir cliqué sur "OK"');
    }
    else if(document.all)// ie
        window.external.AddFavorite(url, title);
}

function bookmark(title, url) {
    javascript:bookmarksite(title, url);
}


/**
 * Common JS for creating photo HTML
 */
function create_photo_html(file){
    html = ""
    html += "<div class='photo' id='photo_{0}'>\n".format(file.id)
    html += "  <input id='s_photo_{1}' name='photo_c' value='{1}' type='checkbox'> <img src='{0}'/>\n".format(file.thumbnail_url, file.id)
    html += "  <input id='i_photo_{0}' name='photo' value='{0}' type='hidden'>\n".format(file.id)
    html += ""
    html += ""
    html += "</div>\n"

    return html
}



$(function() {
    // Global Startup Functions

    $(document).ready(function() {
        $(".hover_help").hover(function(e) {
           
           $("#"+$(this).attr("id")+"_hover").show()
          }, function(){
           $("#"+$(this).attr("id")+"_hover").hide()
        });

        $("button").button();
/*        $(".hidden").hide();*/
        // change the department for the logged in user.
        $("#department_select").change(function() {
            location.href = "http://www." + $(this).val() + "/"
        });
        $.datepicker.setDefaults($.datepicker.regional['fr']);
        $(".datePicker").datepicker({
    beforeShow: function(input, inst){
	   console.log(inst.dpDiv.height())
	   console.log(inst.dpDiv)
	   inst.dpDiv.css({marginTop: (input.offsetHeight - 172)+"px", marginLeft: input.offsetWidth + 'px'});

          $(this).dialog("widget").css("z-index", 50000);
    },
            dateFormat:"yy-mm-dd",
	    changeMonth:true,
	    changeYear:true
        });

        //$(".datePicker").datepicker("option", $.datepicker.regional['fr']);
        //$(".datePicker").datepicker("option", "dateFormat","yy-mm-dd");
        
        $(".plugin_img").hide();

        $(".form-row").mouseenter(function() {

            $(".plugin_img", this).show()
        });

        $(".form-row").mouseleave(function() {
            $(".plugin_img", this).hide()
        });

        $(".show_button").click(function(){
            var id = $(this).attr("id")

            $(".side-menu-box").hide();

            $("."+id+"_div").show();

            return false;
        })

        $(".side-menu-box").hide();



    });

    function _ajax_request(url, data, callback, type, method) {
        if (jQuery.isFunction(data)) {
            callback = data;
            data = {};
        }
        return jQuery.ajax({
            type: method,
            url: url,
            data: data,
            success: callback,
            dataType: type,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#view").append(XMLHttpRequest.responseText);
            }
        });
    }

    jQuery.extend({
        put: function(url, data, callback, type) {
            return _ajax_request(url, data, callback, type, 'PUT');
        },

        delete_: function(url, data, callback, type) {
            return _ajax_request(url, data, callback, type, 'DELETE');
        },

        update_object : function(url, form_id, callback) {
            $.put(url, $(form_id).serialize(), callback)
        },

        craete_object : function(url, form_id, callback) {
            $.post(url, $(form_id).serialize(), callback)
        }
    });
    

})

function mailThisPage()

{

    var link = window.location;

    var emailSubject = "Check this out: "+ document.title;

    var emailAddress=prompt("Please enter the recipients email address","");

    window.location  = "mailto:"+emailAddress+"?Subject="+emailSubject+"&body="+link

}

function hover_help(id){
    
    $(".info-box").remove()

    var x = $(this).position().left

    var y = $(this).position().top


    $.get("/help/"+id, function(html) {
        var box = $("<div class='info-box' style='position: absolute; height: 200px; width: 300px; background: white; border: 1px solid #ccc;  left: {0}; top: {1};' ></div>".format(x,y))

        box.html(html)

        box.mouseleave(function(){

            $(".info-box").remove()
        })

        box.appendTo($("body"))
    })


}
(function($) {

    $.fn.extend({
        center: function () {
            return this.each(function() {
                var top = ($(window).height() - $(this).height()) / 2;
                var left = ($(window).width() - $(this).width()) / 2;

                $(this).css({
                    position:'absolute',
                    margin:0,
                    top: (top > 0 ? top : 0)+'px',
                    left: (left > 0 ? left : 0)+'px'
                });
            });
        }
    });
    $.fn.pictureSlide = function(options){
        return this.each(function() {
            var parent = $(this).parent()
            
            html = '<div class="infoslide ui-corner-bottom" style="height: 50px; bottom: 0px; margin: 0; left: 0px; cursor:pointer;">'
                
            html += '<div class="block-header" id="title">{0}</div>'.format(options.title)
            html += '<div class="info-text">{0}</div>'.format(options.text)
            html += '</div>'

            $el = $(html)
            
            $(this).append($el)

	    if (options.click != undefined){
	      $el.click(options.click)
	    }

            $(this).css({
                "position":"reletive"
            })

            $(this).mouseenter(function(e){
                if (!$(this).children(".infoslide").is(":visible")){

                    $(this).children(".infoslide").toggle('slide', {
                        easing: 'easeOutQuint',
                        direction: 'down'
                    }, 1000);
                }
            })

            var width = ($(this).width()-5);
            $(this).children(".infoslide").css({
                width:width + "px"
            });

            $(this).children(".infoslide").mouseleave(function(e){
                if ($(".infoslide").is(":visible")){
                    $(this).toggle('slide', {
                        easing: 'easeOutQuint',
                        direction: 'down'
                    }, 1000);
                }
            })
        });
    }
    $.extend($.fn, {
        caret: function (start, end) {
            var elem = this[0];

            if (elem) {
                // get caret range
                if (typeof start == "undefined") {
                    if (elem.selectionStart) {
                        start = elem.selectionStart;
                        end = elem.selectionEnd;
                    }
                    else if (document.selection) {
                        var val = this.val();
                        var range = document.selection.createRange().duplicate();
                        range.moveEnd("character", val.length)
                        start = (range.text == "" ? val.length : val.lastIndexOf(range.text));

                        range = document.selection.createRange().duplicate();
                        range.moveStart("character", -val.length);
                        end = range.text.length;
                    }
                }
                // set caret range
                else {
                    var val = this.val();

                    if (typeof start != "number") start = -1;
                    if (typeof end != "number") end = -1;
                    if (start < 0) start = 0;
                    if (end > val.length) end = val.length;
                    if (end < start) end = start;
                    if (start > end) start = end;

                    elem.focus();

                    if (elem.selectionStart) {
                        elem.selectionStart = start;
                        elem.selectionEnd = end;
                    }
                    else if (document.selection) {
                        var range = elem.createTextRange();
                        range.collapse(true);
                        range.moveStart("character", start);
                        range.moveEnd("character", end - start);
                        range.select();
                    }
                }

                return {
                    start:start,
                    end:end
                };
            }
        }
    });
})(jQuery);

function startSpinner(element){
    $('<img src="/resources/images/spinner.gif" id="spinner" />').css('position','absolute').hide().appendTo(element);
    //for every field change
    $('#spinner').center().fadeIn();
}

function stopSpinner(){
    $('#spinner').fadeOut(1000, function(){
       
        $('#spinner').remove();
    });
}

