/**
 * Author: Sébastien Éthier (SEconceptWeb.ca)
 * Date: 11-03-18
 * Time: 21:04
 * openBox for www.seigneuriedespatriotes.qc.ca
 */

if (!window.console) {
  var log = window.opera ? window.opera.postError : alert;
  window.console = { log: function(str) { log(str) } };
}

////////////////////////////////////////////////////
// Author : Sebastien Ethier (SEconceptWeb)
// plugin jQuery openBox personnalise
// add popup effect for photo and video
///////////////////////////////////////////////////
(function($, document, window){


    var uniqueInstance;
    var settings = {
          'boxWidth': 640,
          'boxBackgroundColor': '#000',
          'boxBorder':'3px solid #A48B39',
          'speed' : 1800
    };



    //UI
    var $overlay;
    var $boxVideo;
    var $closeVideo;
    var isOpen;
    var needSlideMotion;
    var startTimerHideCloseBtn;

    /**************************
     *  function helper
     *  **********************/

    //get instance singleton
    function getInstance(){

        if(!uniqueInstance)
            return new Methods();

        return uniqueInstance;
    }

    //create DOM element
    function createElem(elem, id, style){
        return $(document.createElement(elem)).attr("id", id).css('cssText',(arguments[2])? style : "");
    }

    /*var methods = {

        init : function(){console.log('init**')},
        show : function(){console.log('show')},
        hide : function(){console.log('hide')}

    }*/

     /**************************
      *  function method
      *  ***********************/

    var Methods = function()
    {
        //constructor :: Expend there
    };

    //init the plugin
    Methods.prototype.init = function(options){

        //create the box

        //console.log($("#overlay").length);
        //create the overlay
        if($("#overlay").length == 0 && $("#boxVideo").length == 0){
            $overlay = createElem("div", "overlay", "display:none");
            $boxVideo = createElem("div", "boxVideo", "display:none");
            //$closeVideo = createElem("A", "closeVideo", "display:none").attr("href","#closeVideo");
            $overlay.bind("click", uniqueInstance.hide);


            //attach UI to DOM
            $boxVideo.prepend($closeVideo);
            $('body').prepend($overlay, $boxVideo);
        }else
        {
            $overlay = $("#overlay");
            $boxVideo = $("#boxVideo");
            //$closeVideo = $boxVideo.find("a#closeVideo");
        }



        return this.each(function(){

            var $this = $(this);//the this inside the function isn't the same outside this



            /*console.log('init**' + arguments.length);

            for(var i=0;i<arguments.length;i++){
                console.log("arguments : " + arguments[i]);

            }*/


            if(typeof options === 'object')
                $.extend(settings, options);

        // console.log('init**' + settings.hasFlash);


            //gather some information

            /*console.log($this.offset().left);
            console.log($this.offset().top);
            console.log($this.children().attr("src"));
            console.log($this.children().offset().top);
            console.log($this.children().offset().left);
            console.log($this.children().width());
            console.log($this.children().height());*/

           // img = $this.children().clone();


           // console.log("***" + $this.children().length);
            //console.log("***" + $this.children()[0].nodeName + " "  + typeof $this.children());

            /*var data = {
               src : $this.children().attr("src"),
               rel : $this.attr("rel"),
               offsetTop : $this.children().offset().top,
               offsetLeft : $this.children().offset().left,
               width : $this.children().width(),
               height : $this.children().height(),
               name : $this[0].hash
            };*/

            var data = new Object();

            if($this.children().length >= 1 && $this.children()[0].nodeName == 'IMG')
                needSlideMotion = true;
            else
                needSlideMotion = false;

            switch(needSlideMotion){

                case true:
                   data = {
                       src : $this.children().attr("src"),
                       offsetTop : $this.children().offset().top,
                       offsetLeft : $this.children().offset().left,
                       width : $this.children().width(),
                       height : $this.children().height()
                   }
                case false:
                    $.extend(data, {
                        rel : $this.attr("rel"),
                        name : $this[0].hash
                    });
                break;
                default:


            }
            //bind with an event click, except for imageavenir
            if(!/imageavenir/.test(data.src))
                $this.bind("click", data, uniqueInstance.show);
        });
    }

    //show the box (ajax request to getAssets.php and animated box)
    Methods.prototype.show = function(evt){

        evt.preventDefault();//jQquery

        if(!isOpen)
        {

            var aminationStarted = false;
            //open overlay
            $overlay.show();

           // console.log("   evt.data.offsetTop   " + evt.data.offsetTop);

            var cssText = "position:absolute;top:"+evt.data.offsetTop +"px;left:"+evt.data.offsetLeft+"px;width:"+evt.data.width+"px;height:"+evt.data.height+"px;z-index:51;background:"+settings.boxBackgroundColor+";border:"+settings.boxBorder+"; margin:0;padding:0;";
            //url("+evt.data.src+") no-repeat top left scroll


            //prepare the img
            var $img = $(new Image());
            $img.attr("src",evt.data.src);
            //$img.width("100%");

            //init the box
            $boxVideo.html("");//init the box
            $boxVideo.append($img);
            $boxVideo.css("cssText", cssText).show();

            var param = new Object();
            param.filename = evt.data.src;
            param.type = evt.data.rel;


            //Check if has flash console.log(settings.hasFlash);
            if(/video/.test(evt.data.rel) && !settings.hasFlash){
                evt.data.rel = "noFlash";
            }else{
                param.mediafile = evt.data.name.replace("#","");

                //console.log("mediaFile=" + param.mediafile.replace("#",""));
            }
            //store the new html form PHP response
            var html;

            $.get("../scripts/getAsset.php", param, function(response, status, xhr) {
                if (status == "success") {

                    html = response.html;

                    var responseWidth = response.width;//
                    var responseHeight = response.height;//

                    $boxVideo.children().replaceWith(html);

                    //animate
                    $boxVideo.dequeue().animate(
                        //{top: ($(window).height() - (settings.boxWidth*evt.data.height/evt.data.width)) /2 , left: ($(window).width() - settings.boxWidth) /2, width:settings.boxWidth, height: (settings.boxWidth*evt.data.height/evt.data.width)},{
                        {top: (($(window).height() - (responseHeight)) /2) + $(window, "html").scrollTop() , left: ($(window).width() - responseWidth) /2, width:responseWidth, height:responseHeight},{
                        duration : settings.speed,
                        complete : function(){

                            //console.log("fini" + $closeVideo);

                           if(typeof $closeVideo == 'undefined' || $closeVideo == null ){
                                uniqueInstance.createCloseVideoBtn();
                                $boxVideo.bind("mousemove", uniqueInstance.mousemove);
                               $boxVideo.bind("mouseleave", uniqueInstance.mouseleave);
                           }

                           isOpen = true;//set flag to true
                        },
                        step : function(now, fx){
                            //console.log(now + " " + fx.prop + " " +  fx.elem);
                            if(fx.prop == 'width'){
                                //console.log(now);
                                $(fx.elem).children("object,img").width(now);

                            }
                            if(fx.prop == 'height'){
                                //console.log(now);
                                $(fx.elem).children("object,img").height(now);

                            }
                        }
                    });
                  }
                if (status == "error") {
                    $.error("Sorry but there was an error: " + xhr.status + " " + xhr.statusText);
                }
            }, "json");


        }
    }

    //hide UI and revome close button
    Methods.prototype.hide = function(evt){
        //console.log('hide**');

        if(evt)
            evt.preventDefault();

        if(isOpen)
        {
            $overlay.hide();
            $boxVideo.hide();
            $boxVideo.unbind("mousemove", uniqueInstance.mousemove);

            $closeVideo.unbind("click");
            $closeVideo.remove();
            clearTimeout(startTimerHideCloseBtn);

            $closeVideo = null;

            //remove object if any
            if(typeof $boxVideo.find("object") == 'object'){
                $boxVideo.find("object").remove();
            }

            isOpen = false;//set flag to true
        }

    }

    //create closeVideoBtn
    Methods.prototype.createCloseVideoBtn = function(){
        //console.log('hide**');

       $closeVideo = createElem("A", "closeVideo","style:display:none;").attr("href","");
       $closeVideo.bind("click", uniqueInstance.hide );
       $boxVideo.append($closeVideo);
    }


    //Event handler for mousemove
    Methods.prototype.mousemove = function(evt){
        evt.stopPropagation();
        //console.log('mousemove' + evt.pageX);

       // console.log("timerA:" + startTimerHideCloseBtn);
        if(startTimerHideCloseBtn == null || typeof startTimerHideCloseBtn == 'undefined'){
            clearTimeout(startTimerHideCloseBtn);
            startTimerHideCloseBtn = setTimeout(timerHideVideoBtn, 3000);
            $closeVideo.fadeIn('fast');
        }


        function timerHideVideoBtn(evt){
            //console.log("BANG!");
            //clearTimeout(startTimerHideCloseBtn);
            startTimerHideCloseBtn = null;
            $closeVideo.hide();
        }
    }

     //Event handler for mousemove
    Methods.prototype.mouseleave= function(evt){
        evt.stopPropagation();
        //console.log('mousemove' + evt.pageX);
        clearInterval(startTimerHideCloseBtn);
        startTimerHideCloseBtn = null;
        $closeVideo.hide();

    }

    /*
    Methods.prototype.load = function(){

            $.load("scripts/getAsset.php", function(response, status, xhr) {
              if (status == "sucess") {

                    alert(response);
              }
              if (status == "error") {
                var msg = "Sorry but there was an error: ";
                $("#error").html(msg + xhr.status + " " + xhr.statusText);
              }
            });

    }
    */


    //plugin core
    $.fn.openBox = function(method, options){

        /*
        console.log("aa" + options);

         if(options)
         {
            $.extend(settings, options);

             console.log(options.location);

         }
         */

         //instance the new unique class
         uniqueInstance = getInstance();
         //console.log(uniqueInstance['show']);

         //uniqueInstance.hide.apply(this, arguments);

        // console.log(uniqueInstance['init']);

        //Method calling logic
         if(uniqueInstance[method]){
              return uniqueInstance[method].apply(this, Array.prototype.slice.call( arguments, 1 )); // methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
         }else if(typeof method === 'object' || !method){

             /*
              for(var i=0;i<arguments.length;i++){
                console.log("arguments : " + arguments[i]);
              }*/


            return uniqueInstance['init'].apply(this, arguments);
         }else{
            $.error( 'Method ' +  method + ' does not exist on jQuery.openBox');
         }
    }

})(jQuery, document, this);



////////////////////////////////////////////////////
// Author : Sebastien Ethier (SEconceptWeb)
// plugin jQuery openLink personnalise
// add fadeIn/Out effect on the box on the homepage
///////////////////////////////////////////////////
(function($){

    var settings = {
            'min_opacity': 0.6,
            'duration_opacity': 1250
    };

    var methods = {

        init : function(options){

            //this is alreay a object jQuery
            return this.each(function(){

                //bind event
                var $this = $(this);

                var $left_banner = $this.find(".left_banner");

                $this.css({"opacity":"1","cursor":"pointer"});

                $this.bind("mouseenter", $.proxy(methods.eventHandler, $left_banner));
                $this.bind("mouseleave", $.proxy(methods.eventHandler, $left_banner));
                $this.bind("click", methods.eventHandler);
            });
        },
        eventHandler:function(evt){
            
            //console.log("aaaaaa" +evt.type);

            switch(evt.type){

                case "mouseenter":

                   //$(evt.currentTarget).dequeue().fadeTo(settings.duration_opacity, 1);

                   if($(this).length > 0){
                        $(this).toggleClass("left_banner_hover");
                   }



                break;

                case "mouseleave":

                   if($(this).length > 0){

                       //console.log("leave");

                        $(this).toggleClass("left_banner_hover");
                   }

                   //$(evt.currentTarget).dequeue().fadeTo(settings.duration_opacity, settings.min_opacity);


                break;

                case "click":

                    window.location.href = $(evt.currentTarget).attr("data-link");

                break;

                default:
            }
        }
    }

    $.fn.openLink = function(method, options){


       if(methods[method])
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
       else if(typeof method === 'object' || !method)
            return methods['init'].apply(this, arguments);
       else
        $.error("Error openLink");

    }
})(jQuery);


////////////////////////////////////////////////////
// Author : Sebastien Ethier (SEconceptWeb)
// plugin Envoie de formulaire
///////////////////////////////////////////////////
(function($){

    var uniqueInstance = null;


    /**************************
     *  function helper
     *  **********************/

    //get instance singleton
    function getInstance(){

        if(!uniqueInstance)
            return new Methods();

        return uniqueInstance;
    }    

    var Methods = function(){}

    Methods.prototype = {

        init : function(){


            /*
            for(var i = 0; i<arguments.length;i++){
                //console.log(i + ")" +arguments[i]);
            }*/

            //In the immediate scope of the plugin function, the this keyword refers to the jQuery object the plugin was invoked on
            return this.each(function(){
                 var $form = $(this);

                  $.event.add($form[0], "submit", uniqueInstance.submitHandler);//$form.bind("submit",uniqueInstance.submitHandler);
            });
        },

        submitHandler : function(evt){

            evt.preventDefault();//
            var $form = $(evt.currentTarget);
            var $fieldset = $form.children("fieldset");
            var $divLoader;
           // console.log( "param" + $form.serialize());

            //console.log(  uniqueInstance.validateField($form)   );

            if(uniqueInstance.validateField($form))
            {
                $.ajax({
                    type: "post",
                    url: $form.attr("action"),
                    data :  $form.serialize(),
                    cache: false,
                    beforeSend: function(jqXHR, settings){
                        $divLoader = $(document.createElement("div")).attr("id","loader");
                        var $loaderImg = $(document.createElement("img")).attr({"src":"../images/loader.gif", "alt":"Image de chargement..."});

                        $form.append($divLoader.append($loaderImg));
                        $fieldset.hide();
                    },
                    success: function(data, textStatus, jqXHR){

                        if(textStatus == "success"){

                            //Track in google analytics (GOAL)
                            if(typeof _gaq != 'undefined')
                                _gaq.push(['_trackPageview','/SendEmail.php']);

                            $divLoader.empty().html(data);

                            var $recommencerBtn = $(document.createElement('A'));
                            $recommencerBtn.attr("href","#");
                            $recommencerBtn.addClass("resetForm");
                            $recommencerBtn.text("recommancer");

                            $divLoader.append($recommencerBtn);

                            $recommencerBtn.bind("click", function(event){
                                event.preventDefault();
                                $divLoader.hide();
                                $fieldset.fadeIn("show", function(){
                                     $form[0].reset();
                                     $form.find("input:first").focus();
                                });
                            }  );
                            

                            //console.log("show message :" + data);


                        }
                    },

                    error: function(jqXHR, textStatus, errorThrown){
                        $.error("ajax error");
                    }
                });
            }

           // console.log(" validateField = " +   uniqueInstance.validateField($(evt.currentTarget))  );
           // console.log("submit");

        },

        callbackMgsHandler : function(event, data, $divLoader, $fieldset){
                            $divLoader.html(data);

                            var $recommencerBtn = $(document.createElement('button'));
                            $recommencerBtn.attr("type","button");
                            $recommencerBtn.addClass("resetForm");

                            $divLoader.append($recommencerBtn);

                            $.event.add($recommencerBtn[0],"click", function(event){
                                $divLoader.hide();
                                $fieldset.fadeIn("show");
                            }  );

        },

        validateField : function(form){

            //console.log(">>> validateField");

                $form = form;

                var formElemArray  = new Array();
                var $elem = $form.find("input[type='text'],input[type='email'], textarea");
                var isFormValid = true;


                $elem.each(function(i){
                    uniqueInstance.hideError.call($elem);
                   // console.log($(this).is("input[type='email']"));
                   // $(this).filter("input[type='email']").val("allo");
                    if($(this).is("input[type='email']")){
                         formElemArray.push({elem : $(this), isValid : uniqueInstance.isValidEmail($(this).val()),  msg :'Courriel invalide'});

                    }else{
                         formElemArray.push({elem : $(this), isValid :uniqueInstance.isNotEmpty($(this).val()), msg: 'Ce champs est demandé'});
                    }
                });


                //for(var i = 0;i<isValid.length;i++){
                 //console.log(String.prototype.slice.call(isValid['elem']) );
                //}

               // if(/false/.test( String.prototype.slice.call(isValid, ",")  )){



                    for(var i = 0; i < formElemArray.length;i++){
                           // console.log("" + isValid[i].isValid);

                           if(formElemArray[i].isValid == false){
                                // console.log("" + $elem.eq(i));
                                //$elem.eq(i).css("border","1px solid red").focus();
                                uniqueInstance.showError.call(formElemArray[i]);
                                isFormValid = false
                           }
                    }

                return isFormValid;
        },


        hideError: function(){
            this.css("border-color","#A48B39");
            this.next().remove();
        },

        showError: function(){

                var $span = $(document.createElement("span"));
                $span.text(this.msg);
                $span.addClass("error");
                this.elem.css("border-color","#FF0000").after($span);
        },


        isValidEmail : function(emailValue){
             return /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(emailValue);
        },

        isNotEmpty : function(value){
             return value.length > 0;
        }
    }


    $.fn.checkForm = function(method, options){

        uniqueInstance = getInstance();

        if(uniqueInstance[method]){
                return uniqueInstance[method].apply(this, Array.prototype.slice.call(arguments, 1))
        }else if(typeof method === 'object' || !method){

               // console.log( uniqueInstance.init);

             //for(var i in method){console.log(i + ")" +method[i]);}

            //console.log(arguments);

                return uniqueInstance['init'].apply(this, arguments);
        }else{
            
            $.error("Error checkForm");

        }
    }


})(jQuery);






/* isDomReady */
$(function(){

    /*************************
     * openLink
     ************************/

    $("#table_champetre, #corporative, #mariage_champetre, #daim, #visite").openLink();


    /*************************
     * openBox
     ************************/
    hasReqestedVersion = swfobject.hasFlashPlayerVersion("10.1.0");

    //cadre gallery
    $("#gallery a[rel='photo']").openBox(); //.css("border","1px solid green");

    //menu et heritage
    $("#menu a.menu[rel='photo'], #heritage a.heritage[rel='photo']").openBox({'boxBorder':'none','boxBackgroundColor':'none'}); //.css("border","1px solid red");

    //cadre video, page d'acceuil & film traffik
    $("#video a[rel='video']").openBox({'hasFlash': hasReqestedVersion}); //.css("border","1px solid red");
    $("#box a[rel='video']").openBox({'hasFlash': hasReqestedVersion}); //.css("border","1px solid red");
    $("#content a[rel='video']").openBox({'hasFlash': hasReqestedVersion}); //.css("border","1px solid red");

    //bas de la page (appel chez Youtube pour video)
    $("a[rel='youtube']").openBox({'hasFlash': hasReqestedVersion});

    //lien externe (le rendu est en page enb html au lieu d'etre un video)
    $("a[rel='external']").openBox();

    $("#commentsform").checkForm({"aaa":"aaa"});


});




