/*
 *	jQuery Custom Buttons v1.1
 *
 *	© Copyright  2011 Biscay Charly (www.biscay-charly.com)
 *	jQuery Custom Buttons is under GPL License
 *
 *	This file is part of jQuery Custom Buttons.
*
*                       jQuery Custom Buttons is free software: you can redistribute it and/or modify
*                       it under the terms of the GNU General Public License as published by
*                       the Free Software Foundation, either version 3 of the License, or
*                       (at your option) any later version.
*
*                       Foobar is distributed in the hope that it will be useful,
*                       but WITHOUT ANY WARRANTY; without even the implied warranty of
*                       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*                       GNU General Public License for more details.
*
*                       You should have received a copy of the GNU General Public License
*                       along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
 */
(function($) {
    $.fn.jcButton = function(params) {
        params = $.extend( {
            gradient: '#e2e2e2 0%, #dbdbdb 50%, #bcbcbc 51%, #fefefe 100%',     // Default  gradient Color
            color: '#333333',               // Default text and tinted icon color
            iconEnable : true,      // Default : icon is visible
            iconPath: 'img/icons/check.png',    // Path to default  icon
            iconTint: true,                  // Default tint icon
            borderRadius: 10,                     // Default  corner radius
            borderColor: 'auto',     // Default border color
            borderWidth: 0,      // Default border width,
            shadowColor: 'auto',  // Default shadow color
            shadowWidth: 2,     // Default shadow width
            shadowHoverWidth: 6        // Default shadow width (mouseover)
        }, params);

        function init ()
        {
            var _self = $(this);
            var btnID;
            var canID;
            var grad;
            var gradPosX  = Array();
            var gradPosY  = Array();
            var gradPosnX = Array();
            var gradPosnY = Array();
            var gradEtape = Array();
            var stepX = 2;
            var stepY = 2;
            var canvas = Array();
            var ctx = Array();
            var ctxIc = Array();
            var myStage = Array();
            var animate = Array();
            var image;
            var btnWidth = 80;
            var btnHeight = 20;
            var label;
            var isIEready = true;
            var shadowColor = params.shadowColor;
            var borderColor = params.borderColor;
            var canvasDisp = '';

            if (navigator.appName == "Microsoft Internet Explorer") {
                isIEready = false;
            }
             if ((!isCanvasSupported)||(!isIEready)) {
                 _self.html('');
             }
            else 
            {
                _self.hide();
                label = _self.html();
                if (_self.is('input')){
                    label = _self.val();
                }
                if ((shadowColor == 'auto')||(shadowColor.length != 7)){
                    shadowColor = params.color;
                }
                if ((borderColor == 'auto')||(borderColor.length != 7)){
                    borderColor = params.color;
                }
                var gradientArray = params.gradient.split(',');
                var moz_gradient = '-moz-linear-gradient(top,';
                var webkit_gradient = '-webkit-gradient(linear, left top, left bottom,';
                var webkit2_gradient = '-webkit-linear-gradient(top,';
                var opera_gradient = '-o-linear-gradient(top,';
                var ms_gradient = '-ms-linear-gradient(top,';
                var default_gradient = 'background: linear-gradient(top,';
                var msie_gradient = 'progid:DXImageTransform.Microsoft.gradient( ';
                $.each(gradientArray, function (ind,colorLigne) {
                    var couleurPos = colorLigne.indexOf('#');
                    var couleur = colorLigne.substr(couleur, 8);
                    var opacityPos = colorLigne.indexOf('%');
                    var opacity = colorLigne.substr(couleurPos+8, opacityPos);
                    moz_gradient += couleur+' '+opacity+',';
                    webkit_gradient += 'color-stop('+opacity+','+couleur+'),';
                    webkit2_gradient += couleur+' '+opacity+',';
                    opera_gradient += couleur+' '+opacity+',';
                    ms_gradient += couleur+' '+opacity+',';
                    default_gradient += couleur+' '+opacity+',';
                    if (ind == 0) {
                        msie_gradient += "startColorstr='"+couleur+"',";
                    }
                    else if (ind == gradientArray.length -1) {
                        msie_gradient += "endColorstr='"+couleur+"'";
                    }
                });
                moz_gradient = moz_gradient.substr(0,moz_gradient.length-1);
                moz_gradient += ')';
                webkit_gradient = webkit_gradient.substr(0,webkit_gradient.length-1);
                webkit_gradient += ')';
                webkit2_gradient = webkit2_gradient.substr(0,webkit2_gradient.length-1);
                webkit2_gradient += ')';
                opera_gradient = opera_gradient.substr(0,opera_gradient.length-1);
                opera_gradient += ')';
                ms_gradient = ms_gradient.substr(0,ms_gradient.length-1);
                ms_gradient += ')';
                default_gradient = default_gradient.substr(0,default_gradient.length-1);
                default_gradient += ')';
                msie_gradient = msie_gradient.substr(0,msie_gradient.length-1);
                msie_gradient += ',GradientType=0 )';
                if ((isCanvasSupported)&&(isIEready)&&(params.iconEnable)) {
                    canvasDisp = '<canvas class="jcButtonCanBtn" width="24" height="20"></canvas><canvas class="jcButtonCanIcon" width="24" height="20"></canvas>';
                }
                _self.after('<span class="jcButton">'+canvasDisp+'<span class="jcButtonLabel">'+label+'</span></span>');
                _self.next(".jcButton").css('color',params.color);
                _self.next(".jcButton").css('background',moz_gradient);
                _self.next(".jcButton").css('background',webkit_gradient);
                _self.next(".jcButton").css('background',webkit2_gradient);
                _self.next(".jcButton").css('background',opera_gradient);
                _self.next(".jcButton").css('background',ms_gradient);
                _self.next(".jcButton").css('background',default_gradient);
                _self.next(".jcButton").css('filter',msie_gradient);
                _self.next(".jcButton").css('border',params.borderWidth+'px solid '+borderColor);
                _self.next(".jcButton").css('-moz-border-radius',params.borderRadius+'px');
                _self.next(".jcButton").css('-webkit-border-radius',params.borderRadius+'px');
                _self.next(".jcButton").css('border-radius',params.borderRadius+'px');
                _self.next(".jcButton").css('-khtml-border-radius',params.borderRadius+'px');
                _self.next(".jcButton").css('position',_self.css('position'));
                _self.next(".jcButton").css('left',_self.css('left'));
                _self.next(".jcButton").css('right',_self.css('right'));
                _self.next(".jcButton").css('top',_self.css('top'));
                _self.next(".jcButton").css('bottom',_self.css('bottom'));
                _self.next(".jcButton").css('marginLeft',_self.css('marginLeft'));
                _self.next(".jcButton").css('marginRight',_self.css('marginRight'));
                _self.next(".jcButton").css('marginTop',_self.css('marginTop'));
                _self.next(".jcButton").css('marginBottom',_self.css('marginBottom'));
                _self.next(".jcButton").css('verticalAlign','middle');
                _self.next(".jcButton").css('-moz-box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                _self.next(".jcButton").css('-webkit-box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                _self.next(".jcButton").css('box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                _self.next(".jcButton").click(function() {
                    if ( (_self.is('a')) && (!_self.attr('onclick'))){
                        if (_self.attr('target') == '_blank'){
                            window.open(_self.attr('href'));
                        }
                        else{
                            document.location.href = _self.attr('href');
                        }
                    }
                    _self.trigger('click');
                });
                _self.next(".jcButton").hover(function()
                {
                    $(this).addClass('jcButtonOver');
                    _self.next(".jcButton").css('-moz-box-shadow','0px 0px  '+params.shadowHoverWidth+'px '+shadowColor);
                    _self.next(".jcButton").css('-webkit-box-shadow','0px 0px  '+params.shadowHoverWidth+'px '+shadowColor);
                    _self.next(".jcButton").css('box-shadow','0px 0px   '+params.shadowHoverWidth+'px '+shadowColor);
                },
                function()
                {
                    $(this).removeClass('jcButtonOver');
                    _self.next(".jcButton").css('-moz-box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                    _self.next(".jcButton").css('-webkit-box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                    _self.next(".jcButton").css('box-shadow','0px 0px '+params.shadowWidth+'px '+shadowColor);
                });
                if ((!isCanvasSupported)||(!isIEready)||(!params.iconEnable))
                {
                    _self.next('.jcButton').css('paddingLeft','16px');
                }
                else
                {
                    var image = new Image();
                    image.onload = function(){
                        var els = _self.next(".jcButton").find('.jcButtonCanBtn').get();
                        $.each(els,function(i,v){
                            canvas[i]    = els[i];
                            ctx[i] = canvas[i].getContext('2d');
                            gradPosX[i]  = 2;
                            gradPosY[i]  = 10-6;
                            gradPosnX[i] = 12;
                            gradPosnY[i] = 10+6;
                            gradEtape[i] = 0;
                            animate[i]  = false;
                            $(canvas[i]).css('cursor','pointer');
                            ctx[i].strokeStyle = "rgba(0,0,0,1)";
                            ctx[i].fillStyle = "rgba(0,0,0,1)";
                            ctx[i].beginPath();
                            ctx[i].arc(12, 10, 10, 0, 2 * Math.PI, false);
                            ctx[i].closePath();
                            ctx[i].fill();
                        });
                        var els = _self.next(".jcButton").find('.jcButtonCanIcon').get();
                        $.each(els,function(i,v){
                            ctxIc[i] = els[i].getContext('2d');
                            ctxIc[i].globalCompositeOperation = "source-over";
                            ctxIc[i].drawImage(image,7,5);
                            if (params.iconTint)
                            {
                                ctxIc[i].globalCompositeOperation = "source-atop";
                                ctxIc[i].fillStyle = params.color;
                                ctxIc[i].fillRect(6,4,12,12);
                                ctxIc[i].globalCompositeOperation = "source-over";
                            }
                        });
                        setInterval(function(){
                            $.each(canvas,function(i,v){
                                ctx[i] = canvas[i].getContext('2d');
                                ctx[i].clearRect(0,0,40,20); // clear canvas
                                if ($(canvas[i]).parent().is('.jcButtonOver'))
                                {
                                    if ((gradEtape[i] == 0) && (gradPosX[i] < 24))
                                    {
                                        gradPosX[i]=gradPosX[i]+stepX;
                                        gradPosnX[i]=gradPosnX[i]-stepX;
                                    }
                                    else if ((gradEtape[i] == 0) && (gradPosX[i] >= 24))
                                    {
                                        gradPosX[i] = 24;
                                        gradPosnX[i] = 3;
                                        gradEtape[i] =1;
                                    }
                                    else if ((gradEtape[i] == 1) && (gradPosY[i] < 20/2+12))
                                    {
                                        gradPosY[i] = gradPosY[i]+stepY;
                                        gradPosnY[i] = gradPosnY[i]-stepY;
                                    }
                                    else if ((gradEtape[i] == 1) && (gradPosY[i] >= 20/2+12))
                                    {
                                        gradEtape[i] = 2;
                                    }
                                    else if ((gradEtape[i] == 2) && (gradPosX[i] > 2))
                                    {
                                        gradPosX[i] = gradPosX[i]-stepX;
                                        gradPosnX[i] = gradPosnX[i]+stepX;
                                    }
                                    else if ((gradEtape[i] == 2) && (gradPosX[i] <= 2))
                                    {
                                        gradPosX[i] = 2;
                                        gradPosnX[i] = 24;
                                        gradEtape[i] = 3;
                                    }
                                    else if ((gradEtape[i] == 3) && (gradPosY[i] > 20/2-12))
                                    {
                                        gradPosY[i] = gradPosY[i]-stepY;
                                        gradPosnY[i] = gradPosnY[i]+stepY;
                                    }
                                    else if ((gradEtape[i] == 3) && (gradPosY[i] <= 20/2-12))
                                    {
                                        gradPosY[i] = 20/2-12;
                                        gradPosnY[i] = 20/2+12;
                                        gradEtape[i] = 0;
                                    }
                                    grad = ctx[i].createLinearGradient(gradPosX[i], gradPosY[i], gradPosnX[i], gradPosnY[i]);
                                    grad.addColorStop(0.3, 'rgba('+hexToRGBA(params.color)+',0)');
                                    grad.addColorStop(0.5, params.color);
                                    grad.addColorStop(0.7, 'rgba('+hexToRGBA(params.color)+',0)');
                                    ctx[i].fillStyle = grad;
                                    ctx[i].beginPath();
                                    ctx[i].arc(12, 20/2, 9, 0, 2 * Math.PI, false);
                                    ctx[i].closePath();
                                    ctx[i].fill();
                                    ctx[i].fillStyle = "rgba(0,0,0,1)";
                                    ctx[i].globalCompositeOperation = "destination-out";
                                    ctx[i].beginPath();
                                    ctx[i].arc(12, 20/2, 7, 0, 2 * Math.PI, false);
                                    ctx[i].closePath();
                                    ctx[i].fill();
                                    ctx[i].globalCompositeOperation = "source-over";
                                }
                            });
                        }, 20);
                    }
                    image.src = params.iconPath;
                }
            }
            function cutHex(h) {
                return (h.charAt(0)=="#") ? h.substring(1,7):h
            }
            function hexToRGBA(hex)
            {
                var rgba = parseInt((cutHex(hex)).substring(0,2),16);
                rgba += ','+ parseInt((cutHex(hex)).substring(2,4),16);
                rgba += ','+ parseInt((cutHex(hex)).substring(4,6),16);
                return rgba;
            }
            function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
                if (typeof stroke == "undefined" ) {
                    stroke = true;
                }
                if (typeof radius === "undefined") {
                    radius = 5;
                }
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.lineTo(x + width - radius, y);
                ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
                ctx.lineTo(x + width, y + height - radius);
                ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
                ctx.lineTo(x + radius, y + height);
                ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
                ctx.lineTo(x, y + radius);
                ctx.quadraticCurveTo(x, y, x + radius, y);
                ctx.closePath();
                if (stroke) {
                    ctx.stroke();
                }
                if (fill) {
                    ctx.fill();
                }
            }
            function isCanvasSupported(){
                var elem = document.createElement('canvas');
                return !!(elem.getContext && elem.getContext('2d'));
            }
            function getInternetExplorerVersion()
            {
                var rv = -1;
                if (navigator.appName == 'Microsoft Internet Explorer')
                {
                    var ua = navigator.userAgent;
                    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null)
                        rv = parseFloat( RegExp.$1 );
                }
                return rv;
            }
        }
        $(this).each(init);
        return $(this);
    }
})(jQuery);
