$(document).ready(function() {
    $('#search').focus(function() {
        $(this).siblings('label').hide();
    });
    $('#search').blur(function() {
        if ($(this).val() == '') $(this).siblings('label').show();
    });

    $('section.content').find('blockquote').each(function() {
        if ($(this).has('q').length == 0) $(this).html('<q>'+$(this).html()+'</q>');
    });

    // Open external links in new window
    $("a[rel*=external]").attr( "target", "_blank" );

    // Align images left/right
    $('#content').find('img[align="right"], img[align="right"]').each(function() {
        if ($(this).attr('align')) {
            $(this).addClass('align-right');
        } else {
            $(this).addClass('align-left');
        }
    });

    // HACK
    $('#nav > li.menuItem_137 > ul.basicMenuSubMenu').remove();

    // Help a menu out
    $('#nav > li:not(.active)').each(function() {
        // Clear active sub-nav when top level item has no sub menu
        $(this).mouseover(function() {
            $('#nav > li.active > ul.basicMenuSubMenu').hide();
        });
        $(this).mouseout(function() {
            $('#nav > li.active > ul.basicMenuSubMenu').show();
        });
    });
})

/**
 * Fired on window resize. Resizes the mask around the gallery and adjusts the
 * gallery position within so it is again centered.
 */
var galleryResize = function()
{
    var width = $(window).width();
    if (width < 1280) {
        $('#gallery-mask').css('width', width);
        $('#gallery-mask').children(":first").css('margin-left', -((1280 - width) / 2));
    } else {
        $('#gallery-mask').css('width', 1280);
        $('#gallery-mask').children(":first").css('margin-left', 0);
    }
}



function slider_buttons() {
  var items = $('.services .buttons li');
  var len = items.length;  
  if (len <= 1) return false;
  var speed = 5000,
    index = 0,
    next = 0;
  var autoplay = function() {
    index = next;
    next = index + 1;
    if (next >= len) next = 0;
    items.eq(index).fadeOut(1000);
	items.eq(next).fadeIn(1000);
  };
  var timer = setInterval(autoplay, speed);
  $('.services .buttons').hover(function() {
    clearInterval(timer);
  }, function() {
    timer = setInterval(autoplay, speed);
  });
}



/**
 * Triggered from the homepage module through Snapp_Assets
 */
var initGallery = function()
{
    var carousel = $('#gallery').jcarousel({
        //auto: 5, // We'll start autoplay when the slides are sufficiently loaded
        scroll: 1,
        wrap: 'circular',
        easing: 'easeInOutQuart',
        animation: 700,
        setupCallback: function() {
            $('.jcarousel-container').css('position', 'inherit');
        },
        itemFirstInCallback: function(carousel, item, idx, state) {
            // Update circular gallery controls
            // Convert idx to usable value (circular)
            var nrOfSlides = $('#gallery-controls').find('li').length;
            var index = idx - 1;
            if (index < 0) {
                if ((index % nrOfSlides) == 0) index = 0;
                else index = nrOfSlides + (index % nrOfSlides);
            } else {
                index = index % nrOfSlides;
            }
            $('#gallery-controls').find('li').removeClass('active');
            $('#gallery-controls').find('li:eq('+index+')').addClass('active');
        },
        initCallback: function(carousel) {
            // Circular controls
            $('#gallery-controls').find('a').click(function() {
                var index = $(this).parent().index();
                $('#gallery-controls').find('li').removeClass('active');
                $('#gallery-controls').find('li:eq('+index+')').addClass('active');
                carousel.scroll(index+1);
            });
            // Previous, Next buttons
            carousel.container.find('.jcarousel-prev, .jcarousel-next').fadeOut();
            carousel.container.mouseenter(function() {
                // Pause auto play
                carousel.stopAuto();
                if ($.browser.msie) $(this).find('.jcarousel-prev, .jcarousel-next').show();
                else $(this).find('.jcarousel-prev, .jcarousel-next').stop(false, true).fadeIn();
            });
            carousel.container.mouseleave(function() {
                // Resume auto play
                carousel.startAuto();
                if ($.browser.msie) $(this).find('.jcarousel-prev, .jcarousel-next').hide();
                else $(this).find('.jcarousel-prev, .jcarousel-next').stop(false, true).fadeOut();
            });

            // Now start preloading the images and initialise any videos
            galleryLoad(carousel, 0, function() {
                carousel.startAuto(5);
            });
        }
    });
    // Setup window resize observer
    $(window).resize(function() {
        galleryResize();
    });
    // In case the window width is less then 1280px
    galleryResize();
};

/**
 * Called recursively; preloads and inserts the next image into the gallery
 * before it calls itself again. At the end a callback is fired.
 */
var galleryLoad = function(carousel, idx, callback)
{
    var nextToLoad = galleryImages[idx];
    // Determine what <li> relates to this image/video
    var li = carousel.list.find('li:eq('+idx+')');
    // Construct image URL
    //var imageSrc = '/cms/image.php?f='+nextToLoad.src+'&s=1280x400&t=1';
    //var imageSrc = '/cms/image.php?f='+nextToLoad.src+'&s=1280x400&t=1&q=100';
    var imageSrc = '/media/'+nextToLoad.src;
    // Preload image
    $.imgpreload(imageSrc, function() {
        //var a = $('<a>')
        //console.log(nextToLoad);
        // Construct <img> element and inject it into the <li>
        if (nextToLoad.url != '') {
            var a = $('<a />')
                .attr({
                    href: nextToLoad.url,
                    title: nextToLoad.title
                });
            $('<img />')
                .attr({
                    src: imageSrc,
                    alt: nextToLoad.title
                })
                .appendTo(a);
            a.appendTo(li);

        } else {
            // Image only
            $('<img />')
                .attr({
                    src: imageSrc,
                    alt: nextToLoad.title
                })
                .appendTo(li);
        }

        //a.appendTo(li);
        // <li> no longer in loading state
        li.removeClass('loading');
        // Determine what to do next
        var next = idx + 1;
        // Check if there is a next
        if (next == galleryImages.length) {
            callback();
        } else {
            galleryLoad(carousel, next, callback);
        }
    });
};


/**
 * Asynchronously load Google Maps
 */
function loadGMapAPI()
{
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initializeGMap";
    document.body.appendChild(script);
}

function initializeGMap()
{
    var myLatlng = new google.maps.LatLng(-27.45478, 153.00723);
    var myOptions = {
        zoom: 16,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true,
        zoomControl: true
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: "Prescience Technology"
    });
}

var initPoll = function(formId)
{
    $('#enquiryForm_'+formId).validate({
         debug:true,
         errorClass: 'validation-advice',
         onfocusout: false,
         onkeyup: false,
         errorElement: 'div',
         errorPlacement: function(error, element) {
             error.insertBefore(element);
         },
         submitHandler: function(form) {
            // Mark form as loading while submitting
            var submit = $(form).find('input[type="submit"]');
            var loading = $('<span />')
                .addClass('loading')
                .css({
                    opacity: 1
                })
                .html('');
            loading.insertAfter(submit);
            submit.hide();

            // Make the form target 'moduleFormRenttobuy::process()''
            $(form).find('input[name="form_type"]').val('formPrescience');

            // Asynchronous POST
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: '/',
                data: $(form).serialize(),
                success: function(data, textStatus, XMLHttpRequest)
                {
                    // Mark results loading state
                    $('#poll').find('fieldset')
                        .html('')
                        .addClass('loading');
                    // Fetch results table asynchronously
                    $.ajax({
                        type: 'GET',
                        dataType: 'json',
                        url: '/poll-results/index/id/'+formId,
                        complete: function(data, textStatus, XMLHttpRequest)
                        {
                            $('#poll').find('fieldset')
                                .removeClass('loading')
                                .html(data.responseText);
                        }
                    });
                },
                error: function() {}
            });
        }
    });
}

/**
 * Redirects user to blog page with the requested archive
 *
 * @param {HTMLElement} <select> element
 */
var showArchive = function(select, url)
{
    var month = $(select).val();
    if (month != '') document.location.href = url+'/month/'+month;
}

var initContactForm = function()
{
    $('#enquiryForm_1 .formElement textarea, #enquiryForm_1 .formElement input[type="text"]').each(function() {
        $(this).focus(function() {
            // Hide label
            $(this).parents('.formElement').find('label').hide();
        });
        $(this).blur(function() {
            // Show label
            if ($(this).val() == '') {
                $(this).parents('.formElement').find('label').show();
            }
        });
    });

    $('#enquiryForm_1').validate({
        debug: false,
        errorClass: 'validation-advice',
        onfocusout: false,
        onkeyup: false,
        errorElement: 'div',
        errorPlacement: function(error, element) {
            // no inline error placement
            var tip = $('<div />')
                .addClass('tip');
            var arrow = $('<span />')
                .addClass('arrow');
            arrow.appendTo(tip);
            error.appendTo(tip);
            //if (!element.hasClass('valid')) {
                tip.appendTo(element.parent());
            //}
        },
        invalidHandler: function(form, validator) {
            $(form.currentTarget).find('div.tip').remove();
        },
        submitHandler: function(form) {
            //form.submit();
        }
    });
}

