// Background Image Fix
try { document.execCommand("BackgroundImageCache", false, true)} catch(e) {};

/*  ------------------------------------------------------------------
    Google Tracking -------------------------------------------------- */
    function ga(category, action, label){
        if(undefined!==window.pageTracker){ 
            pageTracker._trackEvent(category, action , label);
        }
        return;
    };
    function gaPage(url){
        if(undefined!==window.pageTracker){ 
            pageTracker._trackPageview(url);
        }
        return;
    };

/* ------------------------------------------------------------------
    Close Popin ---------------------------------------------------- */
    function closePopin(){
        jQuery.modal.close();
    };


/* JQUERY PREVENT CONFLICT */
(function($) {

/*  ------------------------------------------------------------------
    Animations ------------------------------------------------------- */
    $.easing.backout = function(x, t, b, c, d){
        var s=1.70158;
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    };


/*  ------------------------------------------------------------------
    External Link ---------------------------------------------------- */
    $.extend($.expr[':'],{
        external: function(a,i,m) {
            if(!a.href) { return false; }
            return $(a).is('[rel*="external"]');
        }
    });
    
    $.fn.externalLinks = function() {
        return this.each( function() {
            $("a", this)
                .filter(":external")
                .unbind("click.external")
                .bind("click.external", function(){
                    return !window.open(this.href);
                });
        });
    };


/*  ------------------------------------------------------------------
    Hover function --------------------------------------------------- */
    $.fn.addHover = function(classOver) {
        var classHover = classOver || "over";
        return this.hover(
            function(){ $(this).addClass(classHover); },
            function(){ $("."+classHover).removeClass(classHover); }
        );
    };


/*  ------------------------------------------------------------------
    Fix Input Focus -------------------------------------------------- */
    $.fn.inpFocus = function(settings) {
        // defaults settings
        settings = $.extend({
            classFocus: "inpFocus"
        }, settings);
        return this.each( function() {
           $(this).find("input:text, input:password, textarea, select").each(function(){
                $(this)
                .bind("focus.inpFocus", function(){
                    $(this).addClass(settings.classFocus);
                })
                .bind("blur.inpFocus", function(){
                    $(this).removeClass(settings.classFocus);  
                })
                .blur();// now change all inputs
            });
        });
    };
    

/*  ------------------------------------------------------------------
    Open YouTube Video ----------------------------------------- */
    $.fn.openYouTube = function() {
    // default settings
    var settings = $.extend( {
        w: 395,
        h: 254,
        hd: true,
        autoPlay: true,
        showRelated: false
    },settings);

        return this.each( function() {
            var hd = (settings.hd)? "&hd=1" : "";
            var autoPlay = (settings.autoPlay)? "&autoplay=1" : "";
            var showRelated = (settings.showRelated)? "&rel=1" : "&rel=0";
            var vid = $(this).attr('href').match("[\\?&]v=([^&#]*)");
            vid = vid[1];

            function getYouTube(vid){
                var youtube = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ settings.w +'" height="'+ settings.h +'">';
                    youtube += '<param name="movie" value="http://www.youtube.com/v/'+ vid+hd +autoPlay+showRelated +'"></param>';
                    youtube += '<param name="wmode" value="transparent"></param>';
                    youtube += '<embed src="http://www.youtube.com/v/'+ vid+hd+autoPlay+showRelated +'" type="application/x-shockwave-flash" wmode="transparent" width="'+ settings.w +'" height="'+ settings.h +'"></embed>';
                    youtube += '</object>';
                return youtube;
            };

            // create a modal dialog with the data
            $('<div id="popin" class="loader"></div>').modal({
                closeClass: 'b_close',
                minWidth: settings.w + 45,
                minHeight: null,
                position: [35],
                overlayId: 'overlay',
                onShow:function (dialog) {
                    //Show overlay
                    dialog.overlay.show();

                    //Add content
                    dialog.data.html(getYouTube(vid));
                }
            });
        });
    };


/*  ------------------------------------------------------------------
    Simple Tooltip --------------------------------------------------- */
    $.fn.introPicture = function() {
        var $introBox = $('<div>').css({ position:'absolute', top:'245px', left:'0', width:'170px' }).appendTo(this);
        return $(this).find('.b_number').each( 
            function() {
                var $this = $(this); 
                var tTitle = (this.title);
                this.title = ""; 
                $this.hover(function(){
                    $introBox.html(tTitle);
                    ga('What is ShaToBu - Image Map', 'Mouseover', $.trim($(this).html()));
                },
                function(){
                    $introBox.empty();
                });
        });
    };


/*  ------------------------------------------------------------------
    Disabled Button -------------------------------------------------- */
    $.fn.disableButton = function(disable) {
        var $this = $(this);
        if(disable){
            $this.attr('disabled', 'disabled').css({ cursor:"default", opacity:.5 }); //, opacity:.5
        }else{
            $this.attr('disabled', '').css({ cursor:"pointer", opacity:1 }); //, opacity:1 
        }
        return $this;
    };


/* ------------------------------------------------------------------
    Get HTML Content ------------------------------------------------ */
    $.fn.getContent = function(url, resp) {
        var $html = $('#main', resp).removeAttr('id');

        // Bind Click on button
        $html.find(":button")
            .bind("click.bindEvents", function(){
                $(this)
                    .disableButton(true)
                    .submitPopin(url); 
                return false;
            });

        //Fix IE Hover and Focus
        if($.browser.msie && $.browser.version < 7){
            // Fix button:hover
            $html.find(":button").addHover("overBtn");
            
            //Add Focus
            $html.inpFocus();
        }

        return this.html($html);
    };


/* ------------------------------------------------------------------
    Ajax Call - Submit Popin ---------------------------------------- */
    $.fn.submitPopin = function(url) {
        var $btn = $(this);

        $.ajax({
            type: "POST",
            url: url,
            //Serialize only fields inside Popin
            data: $btn.parents("form:first").serialize(), 
            complete: function () {
                $btn.disableButton(false);
            },
            success: function (resp) {
                // Log the action in Google Analytics
                if(undefined!==window.pageTracker){
                    pageTracker._trackPageview(url);
                }
                
                $("#popin").getContent(url, resp);
            }
        });
        return this;
    };


/*  ------------------------------------------------------------------
    Load Function ---------------------------------------------------- */ 
    $.fn.loadFct = function (lang) {
        
        //On focus, remove text inside input containing a title, put it back if it has not change
        $(function(){
            $("input[type*='text'][title]")
            .bind("focus",function(){ if(this.value==this.title){ this.value=""; } })
            .bind("blur",function(){ if(this.value==""){ this.value=this.title; } });
        });

        
        //Toggle content on details page
        $("#toggle")
            .find('.toggle_item')
            .addClass('close')
            .find('h3')
            .prepend('<span/>')
            .bind('click', function(){ 
                $(this).parent().toggleClass('open').toggleClass('close'); 
                if ($(this).parent().hasClass('open')){
                    var category;
                    switch ($('body').attr('id')){
                        case 'p_details':
                            category = 'Products Details';
                            break;
                        case 'p_faq':
                            category = 'Frequently Asked Questions';
                            break;
                        case 'p_proventechnology':
                            category = 'Proven Technology';
                            break;
                        default:
                            category = 'Toggle';
                    }
                    ga(category, 'Expand Info', $(this).html());
                }
            });

        // Load Info from xCart
        $().loadXCart();

        // External Links
        $().externalLinks();
        
        // Currency Dropdown
        $("li:gt(0)", "ul.currency").each(function(){ $(this).hide(); });
        $("#b_changecurrency").bind('click', function(e){
            e.stopPropagation();
            $(this).parent("li").toggleClass("open");
            $("li:gt(0)", "ul.currency").toggle();
        });
        $("li","ul.currency").bind('click', function(e){
            e.stopPropagation();                  
        });
        /* Close the dropdown when clicking outside */
        $(document).bind("click", function(){
            $("li:eq(0)", "ul.currency").removeClass("open");
            $("li:gt(0)", "ul.currency").hide();
        });


        //Thumbnails - Selected Arrow
        var $op_thumb = $('.op_thumb > li', '#options');
        $op_thumb.find('a').bind('click.op_thumb', function(){
            $op_thumb.removeClass('selected');
            $(this).parent().addClass('selected');
            //Tracking 
            ga('Product Details', 'Thumbnails', $(this).attr('title'));
        });


        var $slider = $('#slider'); 
        if($slider.length > 0) {
            var slides = new Array('/img/products/banner/slide_5.jpg','/img/products/banner/slide_4.jpg','/img/products/banner/slide_3.jpg','/img/products/banner/slide_2.jpg');
            var totalSlideCount = 1 + slides.length;
            //minimum of 2 slides
            if( totalSlideCount > 1 ) {
                //show buttons
                $("#b_slide_prev, #b_slide_next").show();
                 
                // markup contains only a single slide; before starting the slideshow we  
                // append one slide and prepend one slide (to account for prev/next behavior) 
                $slider.prepend('<img src="'+slides.pop()+'" />'); 
                $slider.append('<img src="'+slides.shift()+'" />'); 
         
                // start slideshow 
                $('#slider')
                .cycle({ 
                    startingSlide: 1,
                    timeout:  0, 
                    speed:    500, 
                    prev:    '#b_slide_prev', 
                    next:    '#b_slide_next', 
                    before:   onBefore 
                });    
            }     
        }

        function onBefore(curr, next, opts, fwd) { 
            if (!opts.addSlide) 
                return; 
           
         // have we added all our slides? 
            if (opts.slideCount == totalSlideCount) 
                return; 
 
            // shift or pop from our slide array  
            var nextSlideSrc = fwd ? slides.shift() : slides.pop(); 
             
            // add our next slide 
            opts.addSlide('<img src="'+nextSlideSrc+'" />', fwd == false); 
        }; 

        var $cta = $("#cta");
        // Open STF Popin
        $('.i_email', $cta).bind('click.stf', function(){
            var href = $(this).attr("href");
            $.get(href,
                function(msg){
                    // create a modal dialog with the data
                    $('<div id="popin"></div>').modal({
                        closeClass: 'b_close',
                        minWidth: 485,
                        minHeight: null,
                        position: [35],
                        overlayId: 'overlay',
                        onShow:function (dialog) {
                            //Show overlay
                            dialog.overlay.show();

                            //Add content
                            dialog.data.getContent(href, msg);
                        }
                    });
                }
            ); 
            
            return false;
        });
        
        // Open Newsletter Popin
        $('.i_newsletter').bind('click.newsletter', function(){
            var href = $(this).attr("href");
            $.get(href,
                function(msg){
                    // create a modal dialog with the data
                    $('<div id="popin"></div>').modal({
                        closeClass: 'b_close',
                        minWidth: 485,
                        minHeight: null,
                        position: [35],
                        overlayId: 'overlay',
                        onShow:function (dialog) {
                            //Show overlay
                            dialog.overlay.show();

                            //Add content
                            dialog.data.getContent(href, msg);
                        }
                    });
                }
            ); 
            
            return false;
        });

        // Open Facebook in New Window
        $('.i_facebook', $cta).bind('click.facebook', function(){
            var share_popup = window.open($(this).attr('href'), 'Shatobu', 'scrollbars=yes,resizable=yes,toolbar=no,location=no,status=no,width=620,height=436');
            if (share_popup) { share_popup.focus(); }
            return !share_popup;
        });

        // Open Youtube Video into Popin
        $(".youtube").bind('click', function(){
            $(this).openYouTube();
            return false;
        });

        // What is ShaToBu - Tooltip Number Info 
        $("#introPicture").introPicture();

        //Contact Form Validation
        $("#frm_contact, #frm_retailer, #frm_newsletter")
            .submit(function () {
                var $form = $(this);
                if($form.isValid()){
                    //Newsletter - Submit with ajax
                    if ($form.is('#frm_newsletter')) {
                        var $btn = $(':button', $form);
                        $.ajax({
                            type: "POST",
                            url: $form.attr('action'),
                            //Serialize only fields inside Popin
                            data: $form.serialize(), 
                            complete: function () {
                                $btn.disableButton(false);
                            },
                            success: function (resp) {
                                gaPage("/newsletter/signup-thank-you");
                                $form.html($('#frm_newsletter', resp).html());
                            }
                        });
                        return false;
                    }
                    return true;
                }else{
                    return false;
                }
            });

        /* Add to cart Button (Read Doc ajax-addtocart.txt) */
        function getQty(str){
            var rg = /(.*:?)"changed":(.*)}},(.*:?)/g;
            var qty = str.match(rg);
            qty = RegExp.$2

            return qty;
        }

        $("#b_addtocart").bind('click', function(){
            var $btn = $(this);
            var $form = $("#frm_product");
            var $form_msg = $('#form_msg');
            var lng_msg = {};

            $btn.disableButton(true)//.find('span').html('sending...');
            
            if(lang == 'fr_CAD'){
                lng_msg.qty = "Oups ! Votre commande d&eacute;passe le nombre d'articles que nous avons en stock actuellement ! Les articles qui nous restent en stock seront ajout&eacute;s &agrave; votre panier. Nous proc&eacute;dons &agrave; un r&eacute;approvisionnement et le reste de votre commande sera trait&eacute; dans les plus brefs d&eacute;lais. Veuillez nous excuser pour ce contretemps.";
                lng_msg.success = "Votre panier a bien &eacute;t&eacute; mis &agrave; jour.";
                lng_msg.stock = "Oups ! Nous n'avons pas cet article en stock actuellement. Mais nous sommes en cours de r&eacute;approvisionnement et cet article sera bient&ocirc;t &agrave; nouveau disponible.";
            }else{
                lng_msg.qty = "Oops! Your order exceeds the quantity of this item we have in stock right now! We have added what we have available to your Shopping Cart, and will refill our inventory, so the rest of your order can be processed soon. We apologize for the inconvenience.";
                lng_msg.success = "Your cart has been successfully updated.";
                lng_msg.stock = "Oops! We do not have this item in stock right now. But we are refilling our inventory, and this item will be available again soon. We apologize for the inconvenience.";
            }

            $.ajax({ 
                url: $form.attr('action'), 
                data: $form.serialize(), 
                success: function(msg){
                    $btn.disableButton(false);//.find('span').html('Add to cart');
                    //Check if Success
                    if(msg.length > 0){
                        //Check if we have added the same number of items
                        if(getQty(msg) != $('#amount').val()) {
                            $form_msg.fadeOut(function(){ $(this).html(lng_msg.qty).show()});
                        }else{
                            //location.href = '/shop/cart.php';
                            $form_msg.fadeOut(function(){ $(this).html(lng_msg.success).show()});
                        }
                        $().loadXCart();
                    }
                    else {
                        $form_msg.fadeOut(function(){ $(this).html(lng_msg.stock).show()}); //.animate({ dummy: 1 }, 3000).empty();
                    }
            }});

            return false;
        });

         // News
        var $news = $('#news')
        if($news.length > 0) {
            $news.find('.b_popin').bind('click.popin', function(){
                var url = $(this).attr('href');
                
                imgSize      = $(this).attr('rel').split('-');
                imgWidth     = parseInt(imgSize[0]);
                imgHeight    = parseInt(imgSize[1]);
                windowHeight = $(window).height() - 100;
                if(imgHeight>windowHeight){
                    imgWidth  = (windowHeight * imgWidth) / imgHeight;
                    imgHeight = windowHeight;
                }else{
                    imgWidth = imgWidth + 46;
                    imgHeight = null;
                }
                
                // create a modal dialog with the data
                $('<div id="popin"></div>').modal({
                    closeClass: 'b_close',
                    minWidth: imgWidth,
                    minHeight: imgHeight,
                    position: [25],
                    overlayId: 'overlay',
                    onShow:function (dialog) {
                        //Show overlay
                        dialog.overlay.show();
                        //Add content
                        if(imgHeight!=null){
                            dialog.data.html('<img src="'+ url +'" style="height:'+ (imgHeight-36) +'px;">');
                        }else{
                            dialog.data.html('<img src="'+ url +'">');
                        }
                    }
                });

                return false;
            });
        }
            
        // Proven Technology
            //size 1: minWidth:532
            //size 2: minWidth:515
            //size 3: minWidth:371
            $('#p_proventechnology').find('.b_popin').bind('click.popin', function(){
                var url = $(this).attr('href');
                var title = $(this).attr('title');
                // create a modal dialog with the data
                $('<div id="popin"></div>').modal({
                    closeClass: 'b_close',
                    minWidth:parseInt($(this).attr('rel')),
                    minHeight: null,
                    position: [50],
                    overlayId: 'overlay',
                    onShow:function (dialog) {
                        //Show overlay
                        dialog.overlay.show();

                        //Add content
                        dialog.data.html('<img src="'+ url +'" ><p class="center">' + title + '</p>');
                    }
                });

                return false;
            });
            
           

        //Fix IE
        if($.browser.msie && $.browser.version < 7){
            //For Input Fields
            // Default: { classFocus: "inpFocus" }
            $('form').inpFocus();

            // Fix button:hover
            $(".btn").addHover("overBtn");
        }
                
        return this;
    };
    
})(jQuery);

