var $j = jQuery.noConflict();
$j(document).ready(function () {

    //Class changer for top navigation bar.
//    $j('#navBar').corner("5px");

    $j('#navBarChange').click(function(){
       $j('#menu').toggleClass('bold');
    });
    
    /* Apply corners - using jquery.corner.js instead of PIE for some reason some IE6 browsers don't show these corners */
    $j('#mainWrapper').corner("20px");
    
    $j("#thumbDiv").mouseover(function () {
        $j("#venue").fadeOut("slow");
    });
    
    $j("#bigDiv").mouseout(function () {
        $j("#venue").fadeIn("slow");
    });

    $j(".sideButton").click(function () {
        $j("#date").DatePickerShow();
        return false;
    });

    $j(".topButton").click(function () {
        $j("#startDate").DatePickerShow();
        return false;
    });

    $j("#date").DatePicker({
        format: "d/m/Y",
        date: $j("#date").val(),
        current: $j("#date").val(),
        starts: 1,
        position: "b",
        onBeforeShow: function () {
            $j("#date").DatePickerSetDate($j("#date").val(), true);
        }, onChange: function (formated, dates) {
            $j("#date").val(formated);
            $j("#date").DatePickerHide();
        }
    });

    $j("#homeNewsPodImage img").attr("src", $j(".homeNewsPodImageHidden1 img").attr("src"));
    $j("#homeNewsPodImage img").attr("title", $j(".homeNewsPodImageHidden1 img").attr("title"));
    $j("#homeNewsPodImage img").attr("alt", $j(".homeNewsPodImageHidden1 img").attr("alt"));
    $j(".article1").hover(function () {
        $j("#homeNewsPodImage img").attr("src", $j(".homeNewsPodImageHidden1 img").attr("src"));
        $j("#homeNewsPodImage img").attr("title", $j(".homeNewsPodImageHidden1 img").attr("title"));
        $j("#homeNewsPodImage img").attr("alt", $j(".homeNewsPodImageHidden1 img").attr("alt"));
    });
    $j(".article2").hover(function () {
        $j("#homeNewsPodImage img").attr("src", $j(".homeNewsPodImageHidden2 img").attr("src"));
        $j("#homeNewsPodImage img").attr("title", $j(".homeNewsPodImageHidden2 img").attr("title"));
        $j("#homeNewsPodImage img").attr("alt", $j(".homeNewsPodImageHidden2 img").attr("alt"));
    });
    $j(".article3").hover(function () {
        $j("#homeNewsPodImage img").attr("src", $j(".homeNewsPodImageHidden3 img").attr("src"));
        $j("#homeNewsPodImage img").attr("title", $j(".homeNewsPodImageHidden3 img").attr("title"));
        $j("#homeNewsPodImage img").attr("alt", $j(".homeNewsPodImageHidden3 img").attr("alt"));
    });
    jQuery.fn.fadeIn = function (speed, callback) {
        return this.animate({
            opacity: "show"
        }, speed, function () {
            if (jQuery.browser.msie) {
                this.style.removeAttribute("filter");
            }
            if (jQuery.isFunction(callback)) {
                callback();
            }
        });
    };
    jQuery.fn.fadeOut = function (speed, callback) {
        return this.animate({
            opacity: "hide"
        }, speed, function () {
            if (jQuery.browser.msie) {
                this.style.removeAttribute("filter");
            }
            if (jQuery.isFunction(callback)) {
                callback();
            }
        });
    };
    $j("#eventType").change(function () {
        $j("#eventVenues ul li").fadeOut("fast");
        $j("#eventVenues ul").hide("normal", function () {
            $j("#eventVenues ul li, #eventVenues ul").empty();
            $j.getJSON("/index.php?c=venue-finder&a=get-locations&id=" + $j("#eventType").val(), function (locations) {
                $j("#eventVenues ul").html("");
                $j.each(locations, function (i, item) {
                    $j("#eventVenues ul").removeAttr("opacity").append('<li><a href="/venues/' + item.urlTitle + '" title="' + item.location + " - " + item.name + '">' + item.location + " - " + item.name + "</a></li>").fadeIn("fast");
                });
                $j("#eventVenues ul li").show("fast");
            });
        });
    });
    $j("#terms-acceptance").submit(function () {
        if (!$j("#terms-acceptance-field").val() == "1") {
            return false;
        } else {
            return true;
        }
    });
    $j(".videoLink").click(function () {
        $j(".videoHolder").ajaxStart(function () {
            $j(this).empty().html('<img src="/images/ajax-loader.gif" align="center" style="padding-top: 90px; padding-left: 200px;" />');
            return false;
        });
        $j("#videoTitle").html($j(this).attr("title")).fadeIn();
        $j.ajax({
            type: "POST",
            url: "/index.php?c=videos&a=find-video&id=" + $j(this).attr("rel") + "&videoType=" + $j(this).attr("rel"),
            dataType: "json",
            success: function (videos) {
                $j(".videoHolder").html(videos).fadeIn();
            }
        });
        return true;
    });
    $j("#email_address").blur(function () {
        $j("a#signUpLink").attr("href", "/sign-up/modal?email_address=" + $j("#email_address").val());
        $j("a#signUpLink").attr("rel", "shadowbox; width=550; height=580;");
        Shadowbox.setup();
        return false;
    });
    $j(".closeShadowBox").click(function () {
        window.parent.Shadowbox.close();
        return false;
    });
    $j(".reloadParent").click(function () {
        parent.location.reload();
        window.parent.Shadowbox.close();
        return false;
    });
    $j(".popup").live('click', function () {
        window.open($j(this).attr("href"));
        return false;
    });
    $j(".back").click(function () {
        history.back();
        return false;
    });
    $j(".printCurrentWindow").click(function () {
        window.print();
        return false;
    });

    //Send action request to Google and Clicky for outbound links
    $j("a[href*='http://']:not([href*='" + window.location.hostname + "'])").bind("click", function (e) {
        _gaq.push(["_trackEvent", "Outbound", jQuery(this).context.hostname, jQuery(this).attr("href")]);
        clicky.log($j(this).attr("href"), $j(this).attr("title"), "outbound");
    });
    
    /* Set up document tracking for analytics */
    $j('a').click(function(){
          href = $j(this).attr('href') ? $j(this).attr('href') : '';
          href_lower = href.toLowerCase(); 
          if(href_lower.substr(-3) == "pdf" || href_lower.substr(-3) == "xls" || href_lower.substr(-3) == "doc") {
            _gaq.push(['_trackEvent', 'Document', 'Download', href]);
          }
          if(href_lower.substr(0, 7) == "mailto:") {
           _gaq.push(['_trackEvent', 'EmailLink', 'Open', href]);
          }
         });

    //Send an action request to google for which search button was pressed.
    $j('.searchButton').click(function () {
        _gaq.push(["_trackEvent", "Search Form", "Search Form Used", $j(this).attr('id')]);
    });

    //Send action request to google for video plays
    $j("a[href*=.flv]").flowplayer({src: '/swf/flowplayer-3.2.5.swf', wmode: 'transparent'}, {
        key: "#$7def0ea747ae46b1052",
        plugins: {
            controls: {
                url: "/swf/flowplayer.controls-3.2.3.swf",
                buttonColor: "rgba(0, 0, 0, 0.9)",
                buttonOverColor: "#000000",
                backgroundColor: "#A6A8AB",
                backgroundGradient: "medium",
                sliderColor: "#FFFFFF",
                sliderBorder: "1px solid #808080",
                volumeSliderColor: "#FFFFFF",
                volumeBorder: "1px solid #808080",
                timeColor: "#000000",
                durationColor: "#535353"
            }
        },
        clip: {
            autoPlay: true
        },
        canvas: {
            backgroundColor: '#987290;',
            backgroundGradient: 'medium'
        },
        onLoad: function() {
           _gaq.push(["_trackEvent", "Video Play", "Play", $j("a[href*=.flv]").attr('title')]);
            clicky.log($j("a[href*=.flv]").attr('href'), $j("a[href*=.flv]").attr('title'), "download");
        },
        onBeforeFinish: function () {
            $j(this).unload();
        }
    });

    /* Home page what clients say sliding video */
    $j('#whatClientsSay').click(function() {
       $j(this).toggleClass('promotionButtonBlueOn');
       $j('#whatClientsSayThumb').slideToggle();
       return false;
    });

    /* Select a location list */
    $j('#selectLocation').click(function() {
       $j(this).toggleClass('promotionButtonBlueOn');
       $j('.selectLocations').slideToggle();
       return false;
    });

    if ($j('.tooltip').length !=0) {
        var tooltipWidth = 0;
        if ($j('.tooltip.payment').length != 0) {
            tooltipWidth = 225;
        } else if ($j('.tooltip.olympic-image-map').length != 0) {
            tooltipWidth = 350;
        } else {
            tooltipWidth = 475;
        }
        $j('.tooltip').each(function(i) {
            $j(this).qtip({
               content: $j('.tooltipContent.' + $j(this).attr('id')).html(),
               show: 'mouseover',
               hide: 'mouseout',
               style: {
                  width: tooltipWidth,
                  name: 'light',
                  border: {
                     width: 7,
                     color: '#C3C3C3'
                  },
                  tip: 'bottomLeft'
               },
               position: {
                  corner: {
                     target: 'topMiddle',
                     tooltip: 'bottomLeft'
                  }
              }
            });
        });
    }
    
    /*
     *Literature Downloads Page
     */
    
    //Initially set the first li to on
    $j('#tabs li:first-child').addClass('on');
    
    //Generate the initial list of items
    if ($j('#literatureContainer').length!=0) {
        getLiteratureThumbnails(0);
    }
    
    $j('#tabs li a').live('click', function() {
        getLiteratureThumbnails($j(this).attr("id"));
        $j(this).parent().parent().children('li').removeClass('on');
        $j(this).parent().addClass('on');
        return false;
    });
    
    function getLiteratureThumbnails($id)
    {
        $j.getJSON("/index.php?c=literature&a=get-thumbnails&id=" + $id, function(thumbnails){
            $j("#thumbnails ul").html("");

            $j.each(thumbnails, function (i, item) {
              
              if (i==0) {
                  //Set the main image
                  $j('#literatureImage a').attr('href', item.url);
                  $j('#literatureImage').css('background', 'transparent url(/assets/literature/' + item.image + ') no-repeat top left');
              }
              
              $j('#thumbnails ul').append('<li><a href="' + item.url + '" rel="' + item.image + '" title="Click to view ' + item.name + '" class="thumbLink popup"><img src="/assets/literature/thumbs/' + item.thumbnail + '" width="83" height="118" /></a></li>')
            });
            
            $j('.next').unbind('click');
            $j('.prev').unbind('click');

            //Set up the carousel
            $j("#thumbnails").jCarouselLite({
                btnNext: ".prev",
                btnPrev: ".next",
                speed: 1000,
                visible: 5,
                scroll: 1
            });
            
            

        });


        $j('.thumbLink').live('mouseover', function() {
            $j('#literatureImage a').attr('href', $j(this).attr('href'));
            $j('#literatureImage').css('background', 'transparent url(/assets/literature/' + $j(this).attr("rel") + ') no-repeat top left');
            return false;
        });
    }
    
    
    
    


    //Sets the messages that appear on the form labels to nowt
    jQuery.validator.messages.required = "";

    //
    // front end validation of form submission
    // submitHandler: fires when successful form sent through
    //
    $j('#availabilitySearchForm').validate({
        invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = errors == 1
                    ? 'It appears you have not completed a field.  This has been highlighted above.'
                    : errors + ' fields have not been completed. They have been highlighted above.';
                $j("div.error span").html(message);
                $j("div.error").show();
            } else {
                $j("div.error").hide();
            }
        },
        rules: {
            delegates: "required",
            roomLayout: "required"
        },
        submitHandler: function(form) {
          if ($j('#col2AvailabilityContent').length != 0) {
            _gaq.push(['_trackPageview', '/left-search-form']);
            // do other stuff for a valid form

            var data = {
                venue: [],
                __submit_check: [],
                duration: [],
                date: [],
                delegates: [],
                roomLayout: [],
                ajax: []
            };

            data.venue.push($j('#venues').val());
            data.__submit_check.push($j("#__submit_check").val());
            data.ajax.push($j("#ajax").val());
            data.duration.push($j("#duration").val());
            data.date.push($j("#date").val());
            data.delegates.push($j("#delegatesMain").val());
            data.roomLayout.push($j("#roomLayout").val());

            callAjaxSearch(data);
            return false;
          } else {
              Shadowbox.open({
                content:    '<div id="overlayLoader" style="text-align: center;"><h2 style="margin: 15px 0 15px 0;">Thanks, we are looking into your request, give us a moment...</h1><p><img src="/images/ajax-loader.gif" width="128" height="15" alt="Loading" title="Loading" /></p></div>',
                player:     "html",
                height:     100,
                width:      550,
                options: {
                    overlayOpacity: 0.35,
                    onFinish: form.submit()
                }
            });
          }

       }
     });

});

function showBookingAbandonModal() {
    /*
     * Sets up the links that aren't part of the availability process
     * to fire the prize draw modal window should the availability process be
     * abandoned.
     *
     * Any links with class availabilityLink are deemed part of the process and
     * are ignored.
     */
     $j('a').not('.availabilityLink').not('#sb-nav-close').click(function() {
       var redirectUrl = $j(this).attr('href');
          Shadowbox.open({
            content: '/availability-checker/abandoned',
            player: 'iframe',
            title: 'Sorry you didn\'t find what you were looking for',
            height: 400,
            width: 550,
            options: {
                onClose : function(){ window.location=redirectUrl; return false; }

            }
        });
       
        return false;
    });
}

function callAjaxSearch(data) {

    $j("#col2AvailabilityContent").ajaxStart(function () {
            $j(this).empty().html('<p><img src="/images/availability/availability.png" alt="Availability" title="Availability" width="152" height="38" /></p><p><img src="/images/ajax-loader.gif" align="center" /></p>');
    });

    $j.ajax({
            type: "POST",
            url: "/availability-checker/search",
            dataType: "html",
            data: data,
            success: function (records) {
                $j("#col2AvailabilityContent").html(records);
                $j("#breadcrumbImage").attr("src", "/images/availability/booking-timeline-step-1.png");
                $j('.weekControl').attr('rel',data.date)
            }
        });
}

