/*
* jQuery Floatbox Plugin 1.0.6
* Copyright (c) 2008 Leonardo Rossetti (motw.leo@gmail.com)
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (jQuery) {
    jQuery.floatbox = function (options) {
		//support for jquery 1.0 request by christoph@breidert.net
		var getWidth = function () {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var width;
			if (version > 1) {
				width = $(window).width();
			} else {
				width = document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth;
			}
			return width / 2;
		};
		
		var getHeight = function () {
			var version = parseInt($.prototype.jquery.match(/\d/gim)[1]);
			var width;
			if (version > 1) {
				width = $(window).width();
			} else {
				width = document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth;
			}
			return width / 2;
		};

		
        var settings = $.extend({
            bg : "floatbox-background",
            box : "floatbox-box",
            content : "",
			button: "<a role='button' href='javascript:void(0);' class='close-floatbox'>Fermer</a>",
			desc: "This is a popup box, press esc key to close.",
            fade : false,
			ajax: null,
            bgConfig : {
                position:  "fixed",
                zIndex: 9000,
                width: "100%",
                height: "100%",
                top:  "0px",
                left: "0px",
                backgroundColor: "#000",
                opacity: "0.75",
                display: "none",
                margin: "0",
                padding: "0"
            },
            boxConfig : {
                position :"absolute",
                zIndex: 9001,
                width: getWidth() + "px",
                //marginLeft: "-" + (getWidth() / 2) + "px",
                left:  (getWidth() / 2) + "px",
                height: "auto",
                top: ($(window).scrollTop() + 20 )+"px" ,
                //left: "50%",
                backgroundColor: "#fff",
                display: "none"
            }
        }, options);




        /*********************
        * Ajout des specialite
        **********************/
        if(options.type == 'addSpecialiteRecherche' || options.type == 'addMatiereRecherche' || options.type == 'addSecteurRecherche' )
        {
           settings.boxConfig.height="320px";
           settings.boxConfig.overflow = 'hidden';
           settings.boxConfig.width="445px";
           settings.boxConfig.left = options.position.x;
           settings.boxConfig.top = options.position.y + 20;
           settings.boxConfig.background = 'none repeat scroll 0 0 #E7F2C3';
           settings.bgConfig.opacity = "0";
           settings.button = "<a role='button' href='javascript:void(0);' class='close-floatbox'></a>";
           
        }

        if(options.type == 'fiche' || options.type == 'ficheLocalise')
        {
            settings.button="<a role='button' href='javascript:void(0);' class='close-floatbox'>"+closeFiche+"</a>";
            settings.boxConfig.width="920px";
            settings.boxConfig.left = (($(window).width()-920) / 2) + "px";
        }

        if(options.type == 'ficheSitrahotel' || options.type == 'ficheSitrarestaurant' || options.type == 'ficheSitraevenement' || options.type == 'ficheSitraoffice')
        {
            settings.boxConfig.width="920px";
            settings.boxConfig.left = (($(window).width()-920) / 2) + "px";
             settings.button="<a role='button' href='javascript:void(0);' class='close-floatbox "+options.type+"'>"+closeFiche+"</a>";
        }
        
        
        
        
        if(options.type == 'mire' || options.type == 'mireSt')
        {

              settings.button = "<a role='button' href='javascript:void(0);' class='close-floatbox'></a>";
              settings.boxConfig.width="400px";
              settings.boxConfig.top = (($(window).height() + $(window).scrollTop()) / 2)-78;
              
              //alert( $(window).scrollTop() );
              settings.boxConfig.left = (($(window).width()-326) / 2) + "px";  
                        
        }
        
        if(options.espace=='do')
        {
            settings.boxConfig.background = 'none repeat scroll 0 0 #e2e2e2';
        }
                
        //inserts floatbox and sets its content
        var showBox = function () {
            
			var content = typeof settings.content === "string" ? settings.content : settings.content.clone();
            //inserts the background element in the document
            if(options.type != 'mire')
            {
                $("<div></div>")
                    .bind("click", function () {
                        closeBox();
                    })
            }
            $("<div></div>")
                .attr("id", settings.bg)
                .css(settings.bgConfig)
                .width(($.browser.msie) ? document.body.clientWidth : "100%")
                //.height(($.browser.msie) ? document.body.clientHeight : "100%")
                .appendTo("body");
            //inserts the floating box in the document
            
            if(options.type != 'mire')            
            {
                 $("<div></div>").find(".close-floatbox").bind("click", function () {
                    closeBox();
                })
            }
            $("<div></div>")
                .attr({id: settings.box, role: "alertdialog"}) 
                .html(content)
                .append(settings.button)
                .css(settings.boxConfig)
                .appendTo("body")
                
                //.css("margin-top", "-" + $("#" + settings.box).height() / 2 + "px")

                .end();         
            //checks if it needs to fade or not
            if (settings.fade) {
                $("#" + settings.bg)
                .fadeIn(200, function () {
                    $("div#" + settings.box).fadeIn(200);
                });
            } else {
                $("#" + settings.bg)
                .show()
                .parent().find("#" + settings.box).show();
            }
			//sets if ajax is needed(already detectets if it is POST or GET)
			if (settings.ajax) {
			     
				$.ajax({
					type: settings.ajax.params === "" ? "GET" : "POST",
					url: settings.ajax.url,
					data: settings.ajax.params,
					
					beforeSend: function () {
						$("#" + settings.box).html(settings.ajax.before);
					},
					
					success: function (data) {
					
                          
                          					 
					mapInitializedPopup = false;
					mapGeolocInitialized = false;
						$("#" + settings.box)
							.html(data)
							.append(settings.button)
							.find(".close-floatbox").bind("click", function () {
								closeBox()
							})
						.end();
						
						  


						
						if(options.type == 'addSpecialiteRecherche' || options.type == 'addMatiereRecherche' || options.type == 'addSecteurRecherche')
						{
						    $('.checkbox').jqTransCheckBox({imgPath:'jqtransformplugin/img/'});
						}
						
						//initialisation du diaporama
						 if(options.type == 'ficheSitrahotel' || options.type == 'ficheSitrarestaurant' || options.type == 'ficheSitraevenement' || options.type == 'ficheSitraoffice')
						{
            			$('#slides').slides({
            				preload: true,
            				preloadImage: 'img/loading.gif',
            				play: 5000,
            				pause: 2500,
            				hoverPause: true
            			});
						}
						
						
        		$(".ficheSousTraitant .email").each(function(){
        			var ats, dots, address, i;
        			ats = [ ' at ', ' (at) ', ' [at] ' ];
        			dots = [ ' dot ', ' (dot) ', ' [dot] ' ];
        			address = $(this).html();
        			
        			for ( i = 0; i < ats.length; i++ ) {
        				address = address.replace(ats[i], '@');
        			}
        			
        			address = address.replace(/ dot /g, '.');
        			
        			/*for ( i = 0; i < dots.length; i++ ) {
        				address = address.replace(/dots[i]/g, '.');
        			}*/
        			$(this).html('<a href="mailto:' + address + '"><span>' + address + '</span></a>');
        		});
		        
		        
		        //gestion de l'accordeon
		        
            if($(".accordeon").size() > 0)
            {
                    //necessaire pour cacher les difference donnec contenant les 
                    //donne modifiable dans le formulaire identite
                    $(".accordeon div.subData").hide();
                    
                    $(".accordeon div.subData.identite").show();
                
                     
                    //maintenant on rend cliquable les span du formulaire en element
                    //cliquable pour pouvoir cree l'accordeon
                    $(".accordeon div.toggleSubMenu span.titre").each( function () 
                    {
                        // On stocke le contenu du span : 
                        var TexteSpan = $(this).text();
                        //on remplace
                        $(this).replaceWith('<a href="" title="Afficher le sous-menu" class="lienMenu">' + TexteSpan + '<\/a>') ;  
                               
                            
                    });
                    
                    $(".accordeon a.lienMenu").addClass('open');
                    //on ajoute maintenant un evenement "click" sur chaque lien de notre accordeon
                    $(".accordeon div.toggleSubMenu > a").click( function () 
                    {
                        // Si le sous-menu Žtait dŽjˆ ouvert, on le referme :
                        if ($(this).parent().next("div.subData:visible").length != 0) 
                        {
                             $(this).removeClass("open");
                             $(this).parent().next("div.subData").slideUp("normal", function () { $(this).parent().removeClass("open") } ); 
                        }
                        //sinon on ouvre le menu
                        else
                        {
                            $(".accordeon div.toggleSubMenu > a ").removeClass('open');
                            $(this).addClass("open");
                            $(".accordeon div.subData").slideUp("normal"); 
                            $(this).parent().next("div.subData").slideDown("normal");
                            
  

                        }
                        //on empeche le navigateur de suivre le lien
                        return false; 
                    }); 
            
            }
            
            if($(".toggleSubMenu  a#geolocSitra"))
            {
               $(".toggleSubMenu  a#geolocSitra").click(function()
               {
                    if(!mapInitializedPopup)
                    {
                        //alert('test');
                        initMapPopup(options.latitude, options.longitude);
                    }
               })
               
               if(options.type == 'ficheLocalise')
               {
                  $(".toggleSubMenu  a#geolocSitra").trigger('click');
               }
            }
            
          
            if($(".toggleSubMenu  a#geolocFicheSitra "))
            {
               $(".toggleSubMenu  a#geolocFicheSitra ").click(function()
               {
                    
                    if(!mapGeolocInitialized)
                    {
                        //alert('test');
                        initLocalisationSitraFiche(options.latitude, options.longitude);
                    }
               })
            }
                        
            $('.buttonSearchSitra').click(function()
            {
                  displayMarker();
                  return false;
            })
        
            $('.btnRelancerRechercheHotel').click(function()
            {
                  displayMarker();
                  return false;
            })
            
            
            $('.tri').click(function()
            {
                  if(jQuery(this).attr('rel') == 'etoile')
                  {
                      jQuery('#triPrix').removeClass('triSelected');
                  }
                  
                  if(jQuery(this).attr('rel') == 'prix')
                  {
                      jQuery('#triEtoile').removeClass('triSelected');
                  }
                  triHotel = jQuery(this).attr('rel');
                  jQuery(this).addClass('triSelected');
                  rechargeSelection();
                  //alert(jQuery(this).attr('rel'));
                  return false;
            })
            
            if($( "#tabs" ))
            {
                $( "#tabs" ).tabs();
            }
            
          	$('.dropdown').jqTransSelect({imgPath:'jqtransformplugin/img/'});	
    			  $('.checkbox').jqTransCheckBox({imgPath:'jqtransformplugin/img/'});
    			              
              /*$('#cartePopup').gmap3(
                { action : 'init', 
                  options:{
                  mapTypeId : google.maps.MapTypeId.ROADMAP,
                  center:{lat: 40.65,lng: -73.95}, 
                  zoom: 5
                  }
                }
              );*/
                      		          
					},
					complete: function (XMLHttpRequest, textStatus) {
						if (settings.ajax.finish) {
							settings.ajax.finish(XMLHttpRequest, textStatus);
							
						}
					}/*,
					contentType: "html"*/
				});
			}
        };
        //hides floatingbox and background
        var closeBox = function () {

            if (settings.fade) {
                $("#" + settings.box).fadeOut(200, function () {
                     $("#" + settings.bg).fadeOut(200, function () {
						$("#" + settings.box).remove();
						$("#" + settings.bg).remove();
                    });
                });
            } else {
				//for opera issues hide first and a timeout is needed to remove the elements
				$("#" + settings.box + ",#" + settings.bg).hide();
				setTimeout(function () {
					$("#" + settings.box).remove();
					$("#" + settings.bg).remove();
				}, 500);
            }
        };
        //inits the floatbox
        var init = function () {
            //shows box
            showBox();
			//adds cross browser event to esc key to hide floating box
            $(document).one("keypress", function (e) {
                var escKey = $.browser.mozilla ? 0 : 27;
                if (e.which === escKey && options.type != 'mire') {
                    closeBox();
                }
            })
			.one("keydown", function (e) {
                var escKey = $.browser.mozilla ? 0 : 27;
                if (e.which === escKey && options.type != 'mire') {
                    closeBox();
                }
            });
			//if msie6, adds event to browser scroll to keep floatbox ina fixed position and uses css hack for full background size
	        /*if ($.browser.msie) {
	            $("body, html").css({height: "100%", width: "100%"});
	            $(window).bind("scroll", function () {
	                $("#" + settings.box).css("top", document.documentElement.scrollTop +  ($(window).height() / 2) + "px");
	            });
	        }*/
        };
        //starts the plugin
        init();
    };
})(jQuery);

