/**
 * @name ot.functions.js
 * @copyright (c) 2011. 2012 Stripe Consulting
 */

//jQuery.noConflict();

var OT;


// Hack to avoid conflicts with other libraries which might assign $. Note: not a ready handler
(function ($) {
  // Ready handler
  $(function () {

    /**
     * Instance of the OT class.
     *
     * @constructor
     * @this {OT}
     */
    OT = {
      
      rcData: "", 
    
      /** Set the elements on which we want to replace the font */
      replaceCufon: function () {
        /*if (!$.browser.msie) {
          Cufon.set("fontFamily", "GillSans").replace("h2, .ch, #navigation ul li a, .shop-item h3, .slide-panel .content h2, .slide-panel .content h3, #footer h3 .about-why-use-us p, #panel-welcome h2, #panel-welcome p, #Tabs ul li a, #sign-up a, .testimonials h3, .expertise, .consultants .consultant-name");
        }
        Cufon.set("fontFamily", "ChristopherHand").replace("h1, .home h2, .destinations h2, #Trips h2.pane-title, .sidebar-item h2, .grey-bordered-area h2, .consultant-wrapper h2, .consultant-wrapper h3, .about-us h2");*/
      },
	  
        
      /** Trip sort filters */
      TripSort: function () {
        /** Trip Sort Links */
        // Hide the underscore on each of the sort anchors
        $("#edit-sort-bef-combine .form-item div a").each(function () {
          $(this).text($(this).text().replace("<none>", ""));
          // Apply an anchor target so that the page scrolls back down to the trips grid after sorting
          if ($(this).attr("href").indexOf("#Trips") < 0) {
            $(this).attr("href", $(this).attr("href") + "#Trips");
          }
        });
        
        // Hide any buttons with js-hide class
        $(".js-hide").addClass("hide");
                
        // Hide the apply buttons if they exist
        /*#edit-submit-region-trips,*/
        $("#edit-submit-country-trips, #edit-submit-special-offer-trips").hide();
    
        // Can we sort by trip?
        if ($("#edit-sort-bef-combine-title-asc").length) {
          var TripAsc = $("#edit-sort-bef-combine-title-asc a").length,
            TripDesc = $("#edit-sort-bef-combine-title-desc a").length,
            TripAscClass = "",
            TripDescClass = "";
    
          //if there is a link inside Trip Asc
          if (TripAsc) {
            //then check to see if there is a link inside Trip Desc
            if (TripDesc) {
              //if so then show Trip Sort Asc and hide Trip Desc
              TripAscClass = "ta-sort";
              TripDescClass = "hide";
            } else {
              TripAscClass = "td-sorted";
              TripDescClass = "hide";
            }
          } else {
            TripAscClass = "hide";
            TripDescClass = "ta-sorted";
          }
    
          $("#edit-sort-bef-combine-title-asc").addClass(TripAscClass);
          $("#edit-sort-bef-combine-title-desc").addClass(TripDescClass);
        }
    
    
        /** Country Sort Links */
        if ($("#edit-sort-bef-combine-field-country-tid-asc").length) {
          var CountryAsc = $("#edit-sort-bef-combine-field-country-tid-asc a").length,
            CountryDesc = $("#edit-sort-bef-combine-field-country-tid-desc a").length,
            CountryAscClass = "",
            CountryDescClass = "";
            
          //if there is a link inside Country Asc
          if (CountryAsc) {
            //then check to see if there is a link inside Country Desc
            if (CountryDesc) {
              //if so then show Country Sort Asc and hide Country Desc
              CountryAscClass = "ca-sort";
              CountryDescClass = "hide";
            } else {
              CountryAscClass = "cd-sorted";
              CountryDescClass = "hide";
            }
          } else {
            CountryAscClass = "hide";
            CountryDescClass = "ca-sorted";
          }
    
          $("#edit-sort-bef-combine-name-asc").addClass(CountryAscClass);
          $("#edit-sort-bef-combine-name-desc").addClass(CountryDescClass);
        }
    
        /** Country Sort Links - Name*/
        if ($("#edit-sort-bef-combine-name-asc").length) {
          var CountryAsc = $("#edit-sort-bef-combine-name-asc a").length,
            CountryDesc = $("#edit-sort-bef-combine-name-desc a").length,
            CountryAscClass = "",
            CountryDescClass = "";
            
          //if there is a link inside Country Asc
          if (CountryAsc) {
            //then check to see if there is a link inside Country Desc
            if (CountryDesc) {
              //if so then show Country Sort Asc and hide Country Desc
              CountryAscClass = "ca-sort";
              CountryDescClass = "hide";
            } else {
              CountryAscClass = "cd-sorted";
              CountryDescClass = "hide";
            }
          } else {
            CountryAscClass = "hide";
            CountryDescClass = "ca-sorted";
          }
    
          $("#edit-sort-bef-combine-name-asc").addClass(CountryAscClass);
          $("#edit-sort-bef-combine-name-desc").addClass(CountryDescClass);
        }
        
        
        // Clear form
        $(".views-reset-button .form-submit").unbind("click").bind("click" , function(e) {
          e.preventDefault();
          
          var parentForm = $(this).closest("form");
        
          parentForm.find("select").each(function() {
            $(this).val("All");
          });
          
          parentForm.find(".views-submit-button .form-submit").click();
        });
      },
      
      
      /** Retrieve the list of RegionIDs and Countries as JSON */
      getRCData: function () {
        var self = this, 
          config = "";
          
        self.config = {
          ddlRegion: "",     // id of the region dropdown
          ddlCountry: "",    // id of the country dropdown

          ddlTfRegion: "",     // id of the TF region dropdown
          ddlTfCountry: "",    // id of the TF country dropdown

          options: "",       // html content of the country dropdown
          tripsGrid: false,  // whether or note the event was called from the trips grid filter
          previousRegion: $(".ot-tf-data-region-id-after-ajax").val()
        };
        
        $.getJSON("/rc-json", {}, function(data) {
          self.rcData = data;
          
          // onload if edit-field-region-tid exists and edit-field-region-tid value is not ALL then FilterCountries using edit-field-region-tid value
          
          if ($("#edit-field-region-tid").length) {
            // Set the region and country ddl's
            self.config.ddlRegion = "#edit-field-region-tid";
            self.config.ddlCountry = "#edit-field-country-tid";
            self.config.tripsGrid = true;
            
            // Bind the ddl change event
            self.OnFilterChange(self.config);
          }
//          if ($("#edit-tf-field-region-tid").length && !$(".testimonials-list").length) {
          if ($("#edit-tf-field-region-tid").length) { //&& !$(".testimonials-list").length) {
            // Set the region and country ddl's
            self.config.ddlTfRegion = "#edit-tf-field-region-tid";
            self.config.ddlTfCountry = "#edit-tf-field-country-tid";
            
            // If we are on a region page we set the selected region and filter countries right away
            if ($(".ot-map-data-region-id").length) {
              // Set the region ddl's selected value
              $(self.config.ddlTfRegion).val($(".ot-map-data-region-id").text());
              
              // Filter the countries using the region id
              self.FilterCountries(self.config.ddlTfRegion, self.config);
              
              // Set the country ddl's filtered results
              $(self.config.ddlTfCountry).html(self.config.options);
              
              // Set the region ddl's selected value
              $(self.config.ddlTfCountry).val($(".ot-map-data-country-id").text());
              
              if ($("#edit-field-country-tid").length) {
                $("#edit-field-country-tid").html(self.config.options);
              }
            }
            
            // Bind the ddl change event
            self.OnTfFilterChange(self.config);
          }
        });
      },
      
      /** Bind the ddl change event for the filter dropdowns */
      OnFilterChange: function(config) {
        var self = this;
        
        $(config.ddlRegion).change(function() {
          if (config.tripsGrid) {
            $(".ot-tf-data-region-id-after-ajax").val($(this).find("option:selected").val());
          }
          
          // Filter the countries using the selected region id
          var options = self.FilterCountries(this, config);
          
          //console.log(options);
          
          $(config.ddlCountry).html(options);
        });
        
        $(config.ddlCountry).change(function() {
          $(".ot-tf-data-country-id-after-ajax").val($(this).find("option:selected").val());
          
          //console.log($(".ot-tf-data-country-id-after-ajax").val());
        });
      },
      
      /** Bind the ddl change event for the filter dropdowns */
      OnTfFilterChange: function(config) {
        var self = this;
        
        $(config.ddlTfRegion).change(function() {
          if (config.tripsGrid) {
            $(".ot-tf-data-region-id-after-ajax").val($(this).find("option:selected").val());
          }
          
          // Filter the countries using the selected region id
          var options = self.FilterCountries(this, config);
          
          //console.log(options);
          
          $(config.ddlTfCountry).html(options);
        });
      },
      
      /** FilterCountries */
      FilterCountries: function(el, config) {
        var self = this,  
          selectedRegionVal = $(el).find("option:selected").val();
          
        if (config.previousRegion != "") {
          //selectedRegionVal = config.previousRegion;
        }
        
        config.options = "<option value='All'>- Any -</option>";
        
        // Loop through each JSON item
        $(self.rcData).each(function() {
          if (this.regionid == selectedRegionVal) {
            // Appened the matched country
            config.options += "<option value='" + this.optionValue + "'>" + this.optionDisplay + "</option>";
          }
        });
        
        return config.options;
      },
      
      
      /** FilterCountries */
      FilterCountriesAfterAjax: function(el) {
        var self = this,  
          selectedRegion = $(".ot-tf-data-region-id-after-ajax").val(),
          selectedCountry = $(".ot-tf-data-country-id-after-ajax").val(),
          options = "";
        
        options = "<option value='All'>- Any -</option>";
        
        // Loop through each JSON item
        $(self.rcData).each(function() {
          if (this.regionid == selectedRegion) {
            // Appened the matched country
            options += "<option value='" + this.optionValue + "'>" + this.optionDisplay + "</option>";
          }
        });
        
        $(el).html(options);
        $(el).val(selectedCountry);
        
        $("#advanced-search #edit-tf-field-region-tid").val(selectedRegion);
        $("#advanced-search #edit-tf-field-country-tid").html(options);
        $("#advanced-search #edit-tf-field-country-tid").val(selectedCountry);
        
        self.getRCData();
      },
      
      
      /** Initiate page functionality */
      initPage: function() {
        /** Get url parameters by name */
        function getParameterByName(name) {
          var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
          return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
        }
        
        
        /** Set the hover state opacity for an element */
        function setHoverEffect($el, opacity, hoverOpacity) {
          $el.hover(function () {
            $(this).stop(true, true).fadeTo(500, hoverOpacity);
          }, function () {
            $(this).fadeTo(500, opacity);
          });
        }
        
        
        /** Set opacity on the homepage carousel. Hover effect */
        var $info = $("#carousel:not(.mini)").find("#carousel-info"), 
          $miniInfo = $("#carousel.mini").find("#carousel-info");
          
        if ($("#carousel-info").length && $("#carousel img").length > 1) {
          $info.css({
            opacity: 0.8
          }).show();
          
          $miniInfo.css({
            opacity: 0.4
          });
          
          setHoverEffect($info, 0.8, 1);
          setHoverEffect($miniInfo, 0.4, 0.6);
        }
    
    
        /** Trip filter toggle display */
        $("#advanced-search").hide();
        $(".header-filter .trip-filter").click(function () {
          $("#advanced-search").slideToggle();
    
          return false;
        });
    
    
        /** Trip filter search input - clear on focus */
        $(".trip-filter-textfield").focus(function () {
          $(this).val("");
        });
    
    
        /** FAQ functionality */
        if ($(".faq-page").length) {
          // Hide the faq text
          $(".faq-page .question").next(".faq-answer").hide();
    
          // Show the faq text if querystring passed
          var faqNode = getParameterByName("faq");
          if (faqNode != '') {
            $("." + faqNode).next(".faq-answer").show();
            $("." + faqNode).find("a").attr("class", "bold")
          }
    
          // Reveal the text once the heading is clicked
          $(".faq-page .question").each(function () {
            $(this).find("a").click(function () {
              $(this).toggleClass("bold").parent().next(".faq-answer").slideToggle();
    
              return false;
            });
          });
        }
    
    
        /** Slide panel functionality */
        if ($(".slide-panel").not(".no-slide").length) {
          var slide = $(".slide-panel").not(".no-slide");
    
          // Bind events for each panel
          slide.each(function () {
            var content = $(".content", this),
              timeout, 
              shortDesc = $(this).hasClass("short");
    
            $(this).css({
              "height": "172px"
            }).bind("mouseenter", function () {
              // add a bit of a delay so it doesn't get annoying on rollover
              timeout = setTimeout(function () {
                content.animate({
                  top: shortDesc ? "112px" : "92px"
                }, {
                  queue: false,
                  duration: 300
                }, "easeOutExpo");
              }, 400);
            }).bind("mouseleave", function () {
              clearTimeout(timeout);
    
              content.animate({
                "top": "138px"
              }, {
                queue: false,
                duration: 400
              }, "easeInExpo");
            });
          });
        }
    
    
        /** New accomodation & Special offers */
        if ($(".accommodation .acc-created").length) {
          $(".accommodation .item").each(function () {
            var dateStr = $(this).find(".acc-created").text().split("/"),
              dateCreated = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]),
              dateNow = new Date(), 
              isNew = $(this).find(".acc-override-created").text().toLowerCase() !== "true";
            
            if (isNew) {
              /* New accommodation */
              dateNow.setDate(dateNow.getDate() - 30);
              
              if (dateCreated > dateNow) {
                $(this).addClass("acc-new");
              }
            }
            
            /* Special Offer */
            dateStr = $(this).find(".spx-offer").text();
            if (dateStr.length > 0) {
              dateStr = dateStr.split("/");
              var dateSpx = new Date(dateStr[2], dateStr[1] - 1, dateStr[0]);
    
              dateNow = new Date();
              dateNow.setDate(dateNow.getDate() + 1);
              
              if (dateSpx >= dateNow) {
                $(this).addClass("acc-spx");
                $(this).find(".spx-offer").text("Special Offer").removeClass("hide");
              }
            }      
          });
        }
    
    
        /** Navigation hovers effect */
        $("#navigation ul.menu li").hover(function () {
          $(this).stop().animate({
              backgroundColor:'#3F515F'}, 250);
            }, function () {
              $(this).stop().animate({backgroundColor:'#000'
            }, 200);
        }).each(function() {
          var $anchor = $(this).find("a"), 
            $href = $anchor.attr("href");
          
          if ($href.indexOf("http") >= 0) {
            $anchor.attr("target", "_blank");
          }
        });
        
        
        /** Add extra classes for browser sniffing. ! Temporary until I can sort the positioning of the shop labels */
        if ($.browser.mozilla) {
          $("html").addClass("firefox");
        }
        
        // Apply Css styles
        this.Css3Styles();
      },
      
      
      /** Add css styling, mostly for IE as it does not support advanced css3 selectors */
      Css3Styles: function() {
        if ($.browser.msie) {
        	$("#Tabs div.slide-panel:nth-child(3n+3)").css({ 
        		"margin-right" : "0"
        	});
        	
        	$(".table-data table tr:last td").css({ 
        		"border" : "none"
        	});
        }
        
        $(".sidebar-item.accommodation .item:last, .sidebar-item.what-to-do .item:last, .sidebar-item.testimonials:not(.single) span.more-info.border-bottom:last").css({ 
        	"border" : "none", 
        	"margin-bottom" : "0"
        });
      },
      
      
      /** slideCarousel */
      slideCarousel: function () {
        var root = $("#carousel"),
          data = $(".pane-content img", root),
          slideInterval, 
          slideCount = $(".pane-content img", root).length,
          slideInfo = $("#carousel-info", root),
          slideContainer = $(".pane-content", root),
          oldSlide = 0,
          imgSrc, currentSlide = 0,
          slideSpeed = 8000,
          ItemArr = [],
          slideRotate, 
          isWide = root.hasClass("wide"), // {bool} Is this a wide sized carousel?
          isMini = root.hasClass("mini"), // {bool} Is this a mini sized carousel?
          isBaby = root.hasClass("baby"); // {bool} Is this a baby sized carousel?

        /** This is a description of the slideRotate variable. */
        slideRotate = { /** This is a description of the slideRotate.forwards function. */
          forwards: function () {
            currentSlide = (oldSlide + 1) % slideCount;

            slideContainer.trigger("rotateImages");
          },

          /** This is a description of the slideRotate.backwards function. */
          backwards: function () {
            oldSlide === 0 ? currentSlide = slideCount - 1 : currentSlide = (oldSlide - 1) % slideCount;

            slideContainer.trigger("rotateImages");
          }
        };
        
        // Hide all of the carousel images
        data.hide();
        // Show the first carousel image
        $(data[0]).show();
        
        // Initiate the carousel
        bindRotate();
        initImages();
        if (!isMini && !isWide) {
          bindInfo();
        }
        slideInfo.trigger("updateInfo");
        
        
        /** This is a description of the bindRotate function. */
        function bindRotate() {
          slideContainer.bind("rotateImages", function (e) {
            var $currentSlide = $(data[currentSlide], this);

            $(data[oldSlide], this).stop(true, true).fadeTo(1000, 0);
            $(data[currentSlide], this).stop(true, true).fadeTo(1000, 1);

            /** If the current slide contains a video display the play icon */
            if ($currentSlide.hasClass("youtube")) {
              $("#PlayIcon").show();
              $("#PlayIcon").click(function () {
                displayVideo($currentSlide.data("url"));

                return false;
              });
            } else {
              $("#PlayIcon").hide();
            }

            $("li:eq(" + currentSlide + ")", "#slide-count").addClass("current-slide").siblings().removeClass("current-slide");
            $("#current-number").text(currentSlide + 1);
            
            slideInfo.trigger("updateInfo");
            oldSlide = currentSlide;
          });
        }
        
        
        function displayVideo(url) {
          clearInterval(slideInterval);

          $.fancybox({
            'margin': 0,
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'width': ($.browser.mozilla ? 974 : 975),
            'height': 368,
            'href': url.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': {
              'wmode': 'transparent',
              'allowfullscreen': 'true'
            },
            onClosed: function () {
              slideInterval = setInterval(slideRotate.forwards, slideSpeed);
            },
            showCloseButton: false,
            overlayShow: false
            //overlayOpacity: 0.1
          });
        }
        
        
        /** This is a description of the initImages function. */
        function initImages() {
          ItemArr = $(".pane-content img", root);

          $.each(ItemArr, function (index) {

            $(".youtube").click(function () {
              displayVideo($(this).data("url"));

              return false;
            });

            if (index + 1 === slideCount - 1) {
              slideInterval = setInterval(slideRotate.forwards, slideSpeed);

              carouselController();
            }
          });
        }
        
        /** This is a description of the bindInfo function. */
        function bindInfo() {
          $("#carousel-info", root).bind("updateInfo", function (e) {
            var detailsArr = [$("p", "#carousel-caption"), $("span", "#carousel-tripname"), $("span", "#carousel-countries"), $("a", "#carousel-link")];

            for (var x in detailsArr) {
              if (detailsArr.hasOwnProperty(x)) {
                $(detailsArr[x]).stop().queue(function () {
                  $(detailsArr[0]).text($(data[currentSlide]).data("copy"));
                  $(detailsArr[1]).text($(data[currentSlide]).data("trip"));
                  $(detailsArr[2]).text($(data[currentSlide]).data("country"));
                  $(detailsArr[3]).attr("href", $(data[currentSlide]).data("trip-url"));
                  $(this).dequeue();
                }).animate({
                  color: "#ffffff"
                }, 750, "easeInQuad");
              }
            }

            $(this).animate({
              backgroundColor: $(data[currentSlide]).data("colour"),
              height: "300px"
            }, {
              queue: false,
              duration: 1000
            });
          });
        }
        
        
        /** This is a description of the carouselController function. */
        function carouselController() {
          var newSlide, timeout, controller;

          $('<div id="carousel-controls" class="clear"><div id="carousel-counter"><span id="current-number">1</span>/<span id="total-number">5</span></div><div id="controls"><div><img src="/sites/all/themes/ot/images/slide_control_prev' + (isBaby ? '_baby' : '') + '.png" alt="previous slide" id="prev-slide"/></div><ul id="slide-count"/><div><img src="/sites/all/themes/ot/images/slide_control_next' + (isBaby ? '_baby' : '') + '.png" alt="next slide" id="next-slide"/></div></div></div>').hide().prependTo("#carousel-info").slideDown(1000).parent().animate({
            height: (isBaby ? "170px" : "341px")
          }, "easeOutSine");
          
          $("#total-number").text(slideCount);

          controller = $("#carousel-info", root);
          //$("#carousel-info", root);
          /** If the mouse is over the info panel pause the carousel */
          controller.bind("mouseenter", function () {
            clearInterval(slideInterval);
          }).bind("mouseleave", function () {
            slideInterval = setInterval(slideRotate.forwards, slideSpeed);
          });

          $("#prev-slide", controller).bind("click", function () {
            if ($("img.slide-image", slideContainer).is(":animated")) {
              return;
            } else {
              if ($("#fancybox-wrap").is(":visible")) {
                $.fancybox.close();
              }

              slideRotate.backwards();
            }
          });
          
          $("#next-slide", controller).bind("click", function () {
            if ($("img.slide-image", slideContainer).is(":animated")) {
              return;
            } else {
              if ($("#fancybox-wrap").is(":visible")) {
                $.fancybox.close();
              }
              
              slideRotate.forwards();
            }
          });
          
          var listDisplay = $("#slide-count").css({
            width: (isBaby ? 12 : 17) * slideCount + "px"
          });
          
          // Align the mini carousel indicators
          if (isWide) {
            $(".wide #carousel-controls").css({
              // a: container width, b: control width, c: arrow width including margin & padding
              // ((a - b) / 2) - c)
              "margin-left" : (((974 - $(".wide #slide-count").width()) / 2) - 22) + "px"
            });
          }
          
          if (isMini) {
            $(".mini #carousel-controls").css({
              // a: container width, b: control width, c: arrow width including margin & padding
              // ((a - b) / 2) - c)
              "margin-left" : (((640 - $(".mini #slide-count").width()) / 2) - 22) + "px"
            });
          }
          
          for (var i = 0; i < slideCount; i++) {
            var li = $('<li><img src="/sites/all/themes/ot/images/slide_control_current' + (isBaby ? '_baby' : '') + '.png" height="15" width="15" /></li>').bind("click", function () {
              clearInterval(slideInterval);
              newSlide = listDisplay.children().index(this);

              if (slideCount === 1 || $("img", slideContainer).is(":animated")) {
                return;
              } else {
                if ($("#fancybox-wrap").is(":visible")) {
                  $.fancybox.close();
                }
                currentSlide = newSlide;
                slideContainer.trigger("rotateImages");
              }
            });

            if (i === 0) {
              li.addClass("current-slide");
            }

            listDisplay.append(li);
          }
        }
      }
    };
    
    
    
  /**
   * Initiate functions as needed
   */

    /** Replace page fonts */
    OT.replaceCufon();
    
    
    /** Apply classes to trip sort filters */
    OT.TripSort();
    
    
    /** Set up the trip filter drop downs */
    OT.getRCData();
    
    
    /** Instantiate homepage carousel if present */
    if ($("#carousel").length && $("#carousel img").length > 1) {
      OT.slideCarousel();
    }
    
    
    /** Initiate page functionality */
    OT.initPage();
  });
})(jQuery);

